User Tools

Site Tools


judoshiai-en:lua-en

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
judoshiai-en:lua-en [2025/01/04 00:01] hjokinenjudoshiai-en:lua-en [2025/01/04 00:20] (current) – [SVG + Lua scripts] hjokinen
Line 58: Line 58:
 </code> </code>
 Again you will display text Hello World! File must be in one of the directories Again you will display text Hello World! File must be in one of the directories
 +<code>
 +HOMEDIR/lualib
 +/home/myname/lualib   (Linux)
 +C:\Users\myname\lualib (Windows)
  
-//HOMEDIR/lualib//\\ +HOMEDIR/lualib/lib 
-///home/myname/lualib   (Linux)\\ +  (for example /home/myname/lualib/lib or C:\Users\myname\lualib\lib)
-C:\Users\myname\lualib (Windows)//+
  
-//HOMEDIR/lualib/lib//\\ +JudoShiai/svg-lua 
-  (for example ///home/myname/lualib/lib// or //C:\Users\myname\lualib\lib)// +  (for example /usr/lib/judoshiai/svg-lua or C:\Program Files\JudoShiai\svg-lua)
- +
-//JudoShiai/svg-lua//\\ +
-  (for example ///usr/lib/judoshiai/svg-lua// or //C:\Program Files\JudoShiai\svg-lua)// +
- +
-//JudoShiai/svg-lua/lib//\\ +
-  (for example ///usr/lib/judoshiai/svg-lua/lib// or\\ +
-   //C:\Program Files\JudoShiai\svg-lua/lib)//+
  
 +JudoShiai/svg-lua/lib
 +  (for example /usr/lib/judoshiai/svg-lua/lib or
 +   C:\Program Files\JudoShiai\svg-lua/lib)
 +</code>
 You can have Lua file anywhere, but then you must give the whole path: You can have Lua file anywhere, but then you must give the whole path:
 +<code>
 Hello %[@/PATH/TO/myhello.lua] Hello %[@/PATH/TO/myhello.lua]
 +</code>
 Note: @-character indicates that rest of the text is a path to a file. Also on Windows you must use forward slashes. Note: @-character indicates that rest of the text is a path to a file. Also on Windows you must use forward slashes.
  
Line 82: Line 82:
  
 There are some predefined read-only variables that you can use after their values are set. To set match related variables call your Lua function from an SVG page like this: There are some predefined read-only variables that you can use after their values are set. To set match related variables call your Lua function from an SVG page like this:
 +<code>
 %[require 'handle_match']m23 %[require 'handle_match']m23
 +</code>
 m23 sets the following global predefined read-only variables for the match #23 before running Lua file //handle_match//: m23 sets the following global predefined read-only variables for the match #23 before running Lua file //handle_match//:
  
Line 105: Line 105:
 |JS_legend      |Legend for the match.                                              | |JS_legend      |Legend for the match.                                              |
 |JS_roundnum    |Round number of the match (first round, repechage, etc.).          | |JS_roundnum    |Round number of the match (first round, repechage, etc.).          |
- 
  
  
 To set competitor related variables call your Lua function like this: To set competitor related variables call your Lua function like this:
 +<code>
 %[require 'print_name']m23-1 %[require 'print_name']m23-1
 +</code>
 This will first set white competitor’s name and other data to global variables and then run your Lua file. The following competitor’s variables are set: This will first set white competitor’s name and other data to global variables and then run your Lua file. The following competitor’s variables are set:
  
Line 134: Line 133:
  
 For the blue competitor the Lua call would be: For the blue competitor the Lua call would be:
 +<code>
 %[require 'print_name']m23-2 %[require 'print_name']m23-2
 +</code>
 Lua code is the one surrounded by brackets. You can have any name and arguments. Lua code is the one surrounded by brackets. You can have any name and arguments.
  
Line 147: Line 146:
  
 There are useful functions that start with JS.: There are useful functions that start with JS.:
 +<code>
   JS.sqlrows(sqlcmd)   JS.sqlrows(sqlcmd)
- 
     Run SQL command.     Run SQL command.
- 
     Parameters     Parameters
- 
       sqlrow String. Sql command to perform.       sqlrow String. Sql command to perform.
- 
     Returns     Returns
- 
       Table of tables.       Table of tables.
- 
- 
  
   JS.writesvg(str)   JS.writesvg(str)
- 
     Writes SVG code on canvas.     Writes SVG code on canvas.
- 
     Parameters     Parameters
- 
       str    String. SVG code to write to the document.       str    String. SVG code to write to the document.
- 
     Returns     Returns
- 
       Nothing.       Nothing.
- 
- 
  
   JS.getdata(index)   JS.getdata(index)
- 
     Get data of competitor or category using index.     Get data of competitor or category using index.
- 
     Parameters     Parameters
- 
       index  Integer. Index of the competitor or category.       index  Integer. Index of the competitor or category.
- 
     Returns     Returns
- 
       Table of data.       Table of data.
- 
- 
  
   JS.getmatchbytatami(tatami, number)   JS.getmatchbytatami(tatami, number)
- 
     Get data about match.     Get data about match.
- 
     Parameters     Parameters
- 
       tatami   Integer. Number of the tatami (1...)       tatami   Integer. Number of the tatami (1...)
- 
       number   Integer. Number of the match (1...)       number   Integer. Number of the match (1...)
- 
     Returns     Returns
- 
       Table of data.       Table of data.
- 
- 
  
   JS.getroundname(round)   JS.getroundname(round)
- 
     Get round name of a match.     Get round name of a match.
- 
     Parameters     Parameters
- 
       round  Integer. Round code from database or getmatchbytatami().       round  Integer. Round code from database or getmatchbytatami().
- 
     Returns     Returns
- 
       String that describes the round.       String that describes the round.
- 
- 
  
   JS.setpages(numpages)   JS.setpages(numpages)
- 
     Set total number of pages.     Set total number of pages.
- 
     Parameters     Parameters
- 
       numpages   Integer. Number of pages in the SVG document.       numpages   Integer. Number of pages in the SVG document.
- 
     Returns     Returns
- 
       Nothing.       Nothing.
- 
- 
  
   JS.getpage()   JS.getpage()
- 
     Get the current page number. First page is 1.     Get the current page number. First page is 1.
- 
     Parameters     Parameters
- 
       None       None
- 
     Returns     Returns
- 
       Current page number (integer) starting from 1.       Current page number (integer) starting from 1.
- 
- 
  
   JS.flag2base64(country)   JS.flag2base64(country)
- 
     Writes flag of a country as base64 string to SVG document. Data is from\\     Writes flag of a country as base64 string to SVG document. Data is from\\
   JudoShiai/etc/flags-ioc.   JudoShiai/etc/flags-ioc.
- 
     Parameters     Parameters
- 
       country  String. IOC abbreviation of the country.       country  String. IOC abbreviation of the country.
- 
     Returns     Returns
- 
       Nothing.       Nothing.
- 
- 
  
   JS.error(message)   JS.error(message)
- 
     Opens a window and shows error text.     Opens a window and shows error text.
- 
     Parameters     Parameters
- 
       message  String. Error text.       message  String. Error text.
- 
     Returns     Returns
- 
       Nothing.       Nothing.
- 
- 
  
   JS.print(text)   JS.print(text)
- 
     Prints texts to an open window.     Prints texts to an open window.
- 
     Parameters     Parameters
- 
       text   String. Text to print.       text   String. Text to print.
- 
     Returns     Returns
- 
       Nothing.       Nothing.
- 
- 
  
   JS.getcatdefs()   JS.getcatdefs()
- 
     Get defined category names.     Get defined category names.
- 
     Parameters     Parameters
- 
       None.       None.
- 
     Returns     Returns
- 
       Table of categories for men and women.       Table of categories for men and women.
- 
     Example:     Example:
- 
       m, w = JS.getcatdefs()       m, w = JS.getcatdefs()
- 
       returns table m for men:       returns table m for men:
- 
         {         {
- 
           [1] = "MenU18",           [1] = "MenU18",
- 
           [2] = "MenU21",           [2] = "MenU21",
- 
           [3] = "M",           [3] = "M",
- 
           numentries = 3,           numentries = 3,
- 
         }         }
- 
       and w for women:       and w for women:
- 
         {         {
- 
           [1] = "WomenU18",           [1] = "WomenU18",
- 
           [2] = "WomenU21",           [2] = "WomenU21",
- 
           [3] = "W",           [3] = "W",
- 
           numentries = 3,           numentries = 3,
- 
         }         }
- 
       Tables have entries 'numentries' that tell the lengths of the tables.       Tables have entries 'numentries' that tell the lengths of the tables.
- 
- 
  
   JS.getsvgbyid(filename, id)   JS.getsvgbyid(filename, id)
- 
     Returns group whose id is id.     Returns group whose id is id.
- 
     Parameters     Parameters
- 
       filename   String. Path to the SVG file       filename   String. Path to the SVG file
- 
       id         String. Id of the <g id="xxx">...</g>       id         String. Id of the <g id="xxx">...</g>
- 
     Returns     Returns
- 
       String that contains the group data.       String that contains the group data.
- 
     Example     Example
- 
       svg = JS.getsvgbyid(InstallationDir .. '/svg-lua/lib/mypage.svg',\\       svg = JS.getsvgbyid(InstallationDir .. '/svg-lua/lib/mypage.svg',\\
                         'header')                         'header')
- 
- 
  
   JS.getsvggeometry(filename, id)   JS.getsvggeometry(filename, id)
- 
     Returns position and size of a svg element.     Returns position and size of a svg element.
- 
     Parameters     Parameters
- 
       filename   String. Path to the SVG file       filename   String. Path to the SVG file
- 
       id         String. Id of the <g id="xxx">...</g>       id         String. Id of the <g id="xxx">...</g>
- 
     Returns     Returns
- 
       X and y coordinates of the svg element.       X and y coordinates of the svg element.
- 
       Width and height of the svg element.       Width and height of the svg element.
- 
     Example     Example
- 
       local x, y, w, h = JS.getsvggeometry(InstallationDir ..\\       local x, y, w, h = JS.getsvggeometry(InstallationDir ..\\
                                          '/svg-lua/lib/mypage.svg', 'header')                                          '/svg-lua/lib/mypage.svg', 'header')
- 
- 
  
   JS.askoption(title, options)   JS.askoption(title, options)
- +    Asks user to select one of the options. NOTE: Opened window is modal. 
-    Asks user to select one of the options. NOTE: Opened window is modal.\\ +    While asking all the other functionality is blocked. 
-  While asking all the other functionality is blocked.\\ +    Please make your selection without delay.
-  Please make your selection without delay. +
     Parameters     Parameters
- 
       title    String. Question to ask.       title    String. Question to ask.
- 
       options  String. Options to select from. Options are\\       options  String. Options to select from. Options are\\
                       separated by slashes.                       separated by slashes.
- 
     Returns     Returns
- 
       Number of the selected option starting from 1.       Number of the selected option starting from 1.
- 
     Example     Example
- 
       local color = JS.askoption('Select a color', 'Red/Green/Blue')       local color = JS.askoption('Select a color', 'Red/Green/Blue')
- 
       Color will be 1 for Red, 2 for Green, and 3 for Blue.       Color will be 1 for Red, 2 for Green, and 3 for Blue.
 +</code>
  
 ===== Example ===== ===== Example =====
Line 419: Line 294:
  
 Make a file //pts.lua//. Start with function //pts//: Make a file //pts.lua//. Start with function //pts//:
 +<code>
 function pts(who)                                   -- line 1 function pts(who)                                   -- line 1
- 
     if JS_points_1 > 0 or JS_points_2 > 0 then      -- line 2     if JS_points_1 > 0 or JS_points_2 > 0 then      -- line 2
- 
         if JS_points_1 == JS_points_2 then          -- line 3         if JS_points_1 == JS_points_2 then          -- line 3
- 
             JS.writesvg('DRAW'                    -- line 4             JS.writesvg('DRAW'                    -- line 4
- 
         else                                        -- line 5         else                                        -- line 5
- 
             if who == 1 then                        -- line 6             if who == 1 then                        -- line 6
- 
                 print_points(JS_points_1)           -- line 7                 print_points(JS_points_1)           -- line 7
- 
             else                                    -- line 8             else                                    -- line 8
- 
                 print_points(JS_points_2)           -- line 9                 print_points(JS_points_2)           -- line 9
- 
             end             end
- 
         end         end
- 
     end     end
- 
 end end
 +</code>
 Explanation line by line: Explanation line by line:
  
Line 464: Line 327:
  
 Finally implement function //print_points//: Finally implement function //print_points//:
 +<code>
 function print_points(p)                -- line 1 function print_points(p)                -- line 1
- 
     if p == 0 then                      -- line 2     if p == 0 then                      -- line 2
- 
         JS.writesvg('LOSS'            -- line 3         JS.writesvg('LOSS'            -- line 3
- 
     elseif p == 7 then                  -- line 4     elseif p == 7 then                  -- line 4
- 
         JS.writesvg('5'               -- line 5         JS.writesvg('5'               -- line 5
- 
     elseif p == 11 then                 -- line 6     elseif p == 11 then                 -- line 6
- 
         JS.writesvg('DRAW'            -- line 7         JS.writesvg('DRAW'            -- line 7
- 
     else                                -- line 8     else                                -- line 8
- 
         JS.writesvg(tostring(p))        -- line 9         JS.writesvg(tostring(p))        -- line 9
- 
     end     end
- 
 end end
 +</code>
 Explanation: Explanation:
  
Line 521: Line 374:
 There are two ways to run Lua scripts: There are two ways to run Lua scripts:
  
-  * Embed code to SVG sheets. Lua code is embedded to text by using format\\ +  * Embed code to SVG sheets. Lua code is embedded to text by using format //%[lua_code_here]//
-//%[lua_code_here]//+
   * Run Lua file. There will be a default SVG file where all the printing goes. Note: The default file has no Inkscape specific definitions. When creating SVG files to include them save them as plain SVG.   * Run Lua file. There will be a default SVG file where all the printing goes. Note: The default file has no Inkscape specific definitions. When creating SVG files to include them save them as plain SVG.
  
Line 548: Line 400:
  
 You can run a Lua script by selecting //Results → Run Script.// Everything you write goes between main //<g>// and //</g>// tags. Next example code draws a 50x60 mm rectangle at position 10, 10: You can run a Lua script by selecting //Results → Run Script.// Everything you write goes between main //<g>// and //</g>// tags. Next example code draws a 50x60 mm rectangle at position 10, 10:
 +<code>
 JS.writesvg("<rect x='10' y='10' height='50' width='60' />") JS.writesvg("<rect x='10' y='10' height='50' width='60' />")
 +</code>
 Normally there are many more parameters, like colors, line style, etc. However, it is not necessary to know the SVG format. You can draw a file and name the objects and import the objects one by one. In the following example we assume you have your Lua code in //JudoShiai/svg-lua/mytest.lua// and SVG file in //JudoShiai/svg-lua/svg/mytest.svg//. Normally there are many more parameters, like colors, line style, etc. However, it is not necessary to know the SVG format. You can draw a file and name the objects and import the objects one by one. In the following example we assume you have your Lua code in //JudoShiai/svg-lua/mytest.lua// and SVG file in //JudoShiai/svg-lua/svg/mytest.svg//.
  
 Use Inkscape to draw a rectangle. Set its id = myrect. Save it using //Save As → Plain SVG// (important!) to //mytest.svg//. Your file looks like this: Use Inkscape to draw a rectangle. Set its id = myrect. Save it using //Save As → Plain SVG// (important!) to //mytest.svg//. Your file looks like this:
 +<code>
 <?xml version="1.0" encoding="UTF-8" standalone="no"?> <?xml version="1.0" encoding="UTF-8" standalone="no"?>
- 
 <!-- Created with Inkscape (http:%%//%%www.inkscape.org/) --> <!-- Created with Inkscape (http:%%//%%www.inkscape.org/) -->
- 
- 
  
 <svg <svg
- 
    width="210mm"    width="210mm"
- 
    height="297mm"    height="297mm"
- 
    viewBox="0 0 210 297"    viewBox="0 0 210 297"
- 
    version="1.1"    version="1.1"
- 
    id="svg5"    id="svg5"
- 
    xmlns="http:%%//%%www.w3.org/2000/svg"    xmlns="http:%%//%%www.w3.org/2000/svg"
- 
    xmlns:svg="http:%%//%%www.w3.org/2000/svg">    xmlns:svg="http:%%//%%www.w3.org/2000/svg">
- 
   <defs   <defs
- 
      id="defs2" />      id="defs2" />
- 
   <g   <g
- 
      id="layer1">      id="layer1">
- 
     <rect     <rect
- 
        style="fill:#d5e5ff;stroke:#000000;stroke-width:0.3;...MORE..."        style="fill:#d5e5ff;stroke:#000000;stroke-width:0.3;...MORE..."
- 
        id="myrect"        id="myrect"
- 
        width="23.7"        width="23.7"
- 
        height="18.4"        height="18.4"
- 
        x="11.9"        x="11.9"
- 
        y="11.5" />        y="11.5" />
- 
   </g>   </g>
- 
 </svg> </svg>
 +</code>
  
 Style is a long line. Note the //id="myrect"//. Write the following lines to your Lua file: Style is a long line. Note the //id="myrect"//. Write the following lines to your Lua file:
 +<code>
 local rect = JS.getsvgbyid(LuaScriptDir .. '/svg/mytest.svg', 'myrect') local rect = JS.getsvgbyid(LuaScriptDir .. '/svg/mytest.svg', 'myrect')
 +</code>
 Function //JS.getsvgbyid// reads object //myrect// to local variable //rect. //You can draw it on the SVG canvas simply like this: Function //JS.getsvgbyid// reads object //myrect// to local variable //rect. //You can draw it on the SVG canvas simply like this:
 +<code>
 JS.writesvg(rect) JS.writesvg(rect)
 +</code>
 It will appear at position 11.9, 11.5. Maybe you want to have another one next to it. First you have to know its dimensions: It will appear at position 11.9, 11.5. Maybe you want to have another one next to it. First you have to know its dimensions:
 +<code>
 local x, y, width, height = JS.getsvggeometry(LuaScriptDir .. '/svg/mytest.svg',\\ local x, y, width, height = JS.getsvggeometry(LuaScriptDir .. '/svg/mytest.svg',\\
                           'myrect')                           'myrect')
 +</code>
 Now you can draw a copy shifted by //width//: Now you can draw a copy shifted by //width//:
 +<code>
 JS.writesvg(string.format('<g transform="translate(%d, 0)">', width)) JS.writesvg(string.format('<g transform="translate(%d, 0)">', width))
- 
 JS.writesvg(rect) JS.writesvg(rect)
- 
 JS.writesvg('</g>') JS.writesvg('</g>')
 +</code>
 This way you can make lists just by creating one line that is copied. This way you can make lists just by creating one line that is copied.
  
Line 635: Line 463:
  
 In many countries this will print 3.14, but in the others 3,14. SVG accepts only the dot as a decimal separator. To be on the safe side it is better to convert the float to a string and then replace possible comma with a dot. Function FloatToStr does that: In many countries this will print 3.14, but in the others 3,14. SVG accepts only the dot as a decimal separator. To be on the safe side it is better to convert the float to a string and then replace possible comma with a dot. Function FloatToStr does that:
 +<code>
 function FloatToStr(a) function FloatToStr(a)
- 
   local r = tostring(a)   local r = tostring(a)
- 
   return r:gsub(',', '.')   return r:gsub(',', '.')
- 
 end end
 +</code>
 Now, instead of //%f// you will use //%s// for a string. The previous translate line Now, instead of //%f// you will use //%s// for a string. The previous translate line
 +<code>
 JS.writesvg(string.format('<g transform="translate(%d, 0)">', width)) JS.writesvg(string.format('<g transform="translate(%d, 0)">', width))
 +</code>
 changes to changes to
 +<code>
 JS.writesvg(string.format('<g transform="translate(%s, 0)">',\\ JS.writesvg(string.format('<g transform="translate(%s, 0)">',\\
                         FloatToStr(width))                         FloatToStr(width))
 +</code>
 ==== Page size ==== ==== Page size ====
  
 The default page size is A4 (210mm x 297mm). You can define your own size by having a comment on the first line of the Lua file: The default page size is A4 (210mm x 297mm). You can define your own size by having a comment on the first line of the Lua file:
 +<code>
 -- paper width=300 height=200 -- paper width=300 height=200
 +</code>
 It is possible to have many sizes for the same Lua code. Create a base file. Then include that in the other files: It is possible to have many sizes for the same Lua code. Create a base file. Then include that in the other files:
 +<code>
 -- paper width=300 height=200 -- paper width=300 height=200
- 
 paper_w = 300 paper_w = 300
- 
 paper_h = 200\\ paper_h = 200\\
 require 'mybase' require 'mybase'
 +</code>
  
 Use //paper_w// and //paper_h// for layout design in //mybase.lua//. Use //paper_w// and //paper_h// for layout design in //mybase.lua//.
Line 675: Line 499:
  
 Set the total number of pages first: Set the total number of pages first:
 +<code>
 JS.setpages(3) JS.setpages(3)
 +</code>
 Next draw you page based on the current page number: Next draw you page based on the current page number:
 +<code>
 current_page = JS.getpage() current_page = JS.getpage()
- 
 if current_page == 1 then if current_page == 1 then
- 
   print_first_page()   print_first_page()
- 
 else else
- 
   print_something_else()   print_something_else()
- 
 end end
 +</code>
 Page changes when you click the visible SVG page with the left or right mouse button. In printer dialog you can select the pages as usual. Page changes when you click the visible SVG page with the left or right mouse button. In printer dialog you can select the pages as usual.
  
Line 697: Line 516:
  
 Example: Print members of category //M-90//: Example: Print members of category //M-90//:
 +<code>
 local numrows, tbl = JS.sqlrows( local numrows, tbl = JS.sqlrows(
- 
     'select last,first from competitors where category="M-90"')     'select last,first from competitors where category="M-90"')
- +</code>
  
 //Numrows// tells how many rows //tbl// has. //Tbl// looks like this: //Numrows// tells how many rows //tbl// has. //Tbl// looks like this:
 +<code>
 { {
- 
   1=    {   1=    {
- 
       last= "SCHMIDT",       last= "SCHMIDT",
- 
       first= "Leon",       first= "Leon",
- 
     },     },
- 
   2=    {   2=    {
- 
       last= "NEUMANN",       last= "NEUMANN",
- 
       first= "Maximilian",       first= "Maximilian",
- 
     },     },
- 
   3=    {   3=    {
- 
       last= "CHRISTENSEN",       last= "CHRISTENSEN",
- 
       first= "Frederik",       first= "Frederik",
- 
     },     },
- 
 } }
 +</code>
 There are three rows. You can get last name of the second competitor like this: There are three rows. You can get last name of the second competitor like this:
 +<code>
 last_name = tbl['2']['last'] last_name = tbl['2']['last']
 +</code>
  
judoshiai-en/lua-en.1735974100.txt.gz · Last modified: 2025/01/04 00:01 by hjokinen