473 posts
Location
Poland
Posted 22 February 2012 - 07:21 PM
How do I execute blocks of code that are in form of a table? e.g.
a={ {print("Hello")}, {print("I don't like you")} }
b=a[1]
LUA manual says that the proper syntax is
do block end
but when i replace block with a variable it doesn't work. So, how to execute blocks?
6 posts
Location
Da Bronx, Ny
Posted 22 February 2012 - 07:31 PM
A block is a list of statements; syntactically, a block is the same as a chunk:
block ::= chunk
A block can be explicitly delimited to produce a single statement:
stat ::= do block end
Explicit blocks are useful to control the scope of variable declarations. Explicit blocks are also sometimes used to add a return or break statement in the middle of another block.
The control structures if, while, and repeat have the usual meaning and familiar syntax:
stat ::= while exp do block end
stat ::= repeat block until exp
stat ::= if exp then block {elseif exp then block} [else block] end
473 posts
Location
Poland
Posted 22 February 2012 - 07:55 PM
And how this brings me closer to understanding how you can execute a block stored in a variable instead of being a part of the code? Look, all I want is the proper code that executes a block.
715 posts
Posted 22 February 2012 - 08:05 PM
You have to put your code into a function. You don't even have to name your function, it can be stored as a so called anonymous function:
local a = { function() print("Hello") end, function() print("I don't like you") end }
You can then assign a variable to it and call it from there, like you did in your code…
b = a[1]
b()
… or you can even call it directly from the table by adding the "function brackets" directly after it:
a[1]()
EDIT:As an alternative to cramming all of your code into the table, you can define your function first and then save its reference into the table. Then you'll have to name it though, or else how could you tell the table with what to fill it, right?^^
Example:
function printHello()
print("Hello")
end
function stateOpinion()
print("I don't like you")
end
local a = { printHello, stateOpinion }
473 posts
Location
Poland
Posted 22 February 2012 - 08:47 PM
The first one's much more useful. The only thing i did wrong was not to add function() at the beginning. And I need this for UI function that can be called by other programs. Thanks.