Jump to content




Block Execution


4 replies to this topic

#1 Liraal

  • New Members
  • 477 posts
  • LocationPoland

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?

#2 streetstar5

    FuzzyWuzzy's

  • New Members
  • 6 posts
  • LocationDa 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

#3 Liraal

  • New Members
  • 477 posts
  • LocationPoland

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.

#4 Espen

    Curious Explorer

  • Members
  • 708 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 }


#5 Liraal

  • New Members
  • 477 posts
  • LocationPoland

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.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users