It's not critical, but I wonder why I get an error message (attempt to call global 'print' (a nil value)' in the editor on the code below. I am using print inside a macro. The code runs fine (in the Windows player).
The error message shows up after the second line of the file (no matter what's in the first two lines). It refers the print in the second line of the macro (line ~10). If I comment out that print, there is no error, i.e. the print further down outside the macro don't trigger.
It looks like
- the syntax check in the editor doesn't fully understand macros and global scope.
- displays that error message offset to beginning of file, instead of macro (i.e. if print is on line 5 in the macro, error goes on line 5 of the code)
The same behavior happens when I use table (as described here:
https://wiki.giderosmobile.com/index.php/Macro_Functions )
--distance function
function distance(o1, o2)
return math.sqrt((o1.c - o2.c)*(o1.c - o2.c) + (o1.r - o2.r)*(o1.r - o2.r))
end
--distance macro
-- Note: comma counts as arguments. If called with comma separated arguments, the second one has index 3
-- (...)[3]
DISTANCE @ (|
print("math.sqrt((" .. (...)[1] .. ".c - " .. (...)[3] .. ".c) * (" .. (...)[1] .. ".c - " .. (...)[3] .. ".c) + "
.. "(" .. (...)[1] .. ".r - " .. (...)[3] .. ".r) * (" .. (...)[1] .. ".r - " .. (...)[3] .. ".r))" )
return "math.sqrt((" .. (...)[1] .. ".c - " .. (...)[3] .. ".c) * ( " .. (...)[1] .. ".c - " .. (...)[3] .. ".c) + "
.. "(" .. (...)[1] .. ".r - " .. (...)[3] .. ".r) * (" .. (...)[1] .. ".r - " .. (...)[3] .. ".r))"
|)
-- test data
local o1, o2, o3, zero = {c = -1, r = 1}, {c = 3, r = 4}, {c = -9, r = -9}, {c = 0, r = 0}
print(distance(o1, o2), distance(o1, zero), distance(o2, zero), distance(o3, zero))
print(DISTANCE(o1, o2), DISTANCE(o1, zero), DISTANCE(o2, zero), DISTANCE(o3, zero)) |
Also, it took me a while to figure out how to do a macro that returns an expression (i.e. single line, without declaring local variables in the macro. Should we add a code snipped to the page above?
SUM @ (| return "("..(...)[1] + (...)[3] ..")" |)
print (SUM(1,2) * SUM(3,1)) |
I am using (...)[1] to refer to the first argument directly, and (...)[3] to the second so I can invoke the macro with comma-separated parameters. Commas count as arguments, i.e. DISTANCE(o1, o2) has three parameters. I think the behavior makes sense once you think of it, but it wasn't obvious.
Comments
Hope this helps resolve your issue!?
Also I have added your example to the wiki. Please tell me if it's correct.
I haven't used macros a lot
The code is working.
Also, I dont like when you have a lot of concatenations. So I did this:
Likes: perrochon
you can ask sinistersoft to give you access.
Likes: MoKaLux
https://deluxepixel.com