Can functions be put in/called from tables?

Posted by Eloni on Sun 29 May 2011 08:24 AM — 3 posts, 14,363 views.

#0
Suppose I want to speedwalk. Halfway through the speedwalk there is a chasm I need to surpass, and I can surpass it with any of 3 abilities. I want to surpass with one ability at random.



abilities = {"jump", "climb", "cast fly" } 

function surpassObstacle()

   Send(abilities[math.random(#abilities)])

end



speedWalk = {
	"n",
	"n",
        surpassObstacle(),
	"n",
	"s"

	}



Is it possible to put functions in tables? Alternatively, could I change a variable using a table?

Not sure if Send would be the proper method of delivery.

Thanks for the help, guys!
Amended on Sun 29 May 2011 09:01 AM by Eloni
Australia Forum Administrator #1
You can put functions in tables, certainly, because functions in Lua are (so-called) "first class objects".

However in your example you don't put a function in the table, you call it at table construction time.

This would be putting the function in the table:


speedWalk = {
  "n",
  "n",
  surpassObstacle,
  "n",
  "s"
}


Now the function (and not its result) is in the table. But now you need to determine (when you are speedwalking) that you have a function, and call it.

eg. Something like:


for k, v in ipairs (speedWalk) do
  if type (v) == "string" then
    Send (v)
  elseif type (v) == "function" then
    Send ( v () ) -- call function, return result
  end -- if
end -- for


Untested, but that is the general idea.
#2
Many thanks! It is now time for me to look in to the inpairs function.