Jump to content




Execute code in a table


  • You cannot reply to this topic
3 replies to this topic

#1 doublequestionmark

  • Members
  • 118 posts
  • LocationI honestly don't know

Posted 19 June 2015 - 12:55 AM

ok, so i have a table like this in my cc program:

Table = {
	    "print('Hello')",
	    "print('Im in a table')",
	    "for i=1,10 do print('Tables are cool') end"
}

i need a way to execute the code in the table, for example:

example(Table[3]) -- could print `Tables Are Cool` ten times

how would i go about doing this?

#2 Quintuple Agent

  • Members
  • 107 posts
  • LocationThis page

Posted 19 June 2015 - 01:15 AM

to execute a string all you have to do is
local exeTab = loadstring("print('hello')")
exeTab()
I would suggest reading the lua tutorial page for this
Also an FYI, if the code inside loadstring is invalid and would throw an error the exeTab return nil plus an error message
From the tutorial page

Quote

print(loadstring("i i"))
--> nil [string "i i"]:1: `=' expected near `i'


#3 Dog

  • Members
  • 1,179 posts
  • LocationEarth orbit

Posted 19 June 2015 - 01:29 AM

If the table entries don't need to be strings, you could do something like this...
local myTable = { function() print('hello') end, function() print("I'm in a table") end, function() for i = 1, 10 do print('Tables are cool') end end }

then you could call myTable[3]() and it would print 'Tables are cool' ten times.

#4 MKlegoman357

  • Members
  • 1,170 posts
  • LocationKaunas, Lithuania

Posted 19 June 2015 - 04:56 AM

Dog's right. Even though compiling Lua code on the fly us 'cool n stuff' but it's not that efficient. If possible please stay with actual functions instead of strings. You could also tell us why you need it so we could suggest to you the best solution.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users