Notice: Any messages purporting to come from this site telling you that your password has expired, or that you need to verify your details, confirm your email, resolve issues, making threats, or asking for money, are
spam. We do not email users with any such messages. If you have lost your password you can obtain a new one by using the
password reset link.
Due to spam on this forum, all posts now need moderator approval.
Entire forum
➜ MUSHclient
➜ Lua
➜ Can functions be put in/called from tables?
Can functions be put in/called from tables?
|
It is now over 60 days since the last post. This thread is closed.
Refresh page
Posted by
| Eloni
(28 posts) Bio
|
Date
| Sun 29 May 2011 08:24 AM (UTC) Amended on Sun 29 May 2011 09:01 AM (UTC) by Eloni
|
Message
| 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! | Top |
|
Posted by
| Nick Gammon
Australia (23,133 posts) Bio
Forum Administrator |
Date
| Reply #1 on Sun 29 May 2011 09:00 AM (UTC) |
Message
| 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. |
- Nick Gammon
www.gammon.com.au, www.mushclient.com | Top |
|
Posted by
| Eloni
(28 posts) Bio
|
Date
| Reply #2 on Sun 29 May 2011 09:08 AM (UTC) |
Message
| Many thanks! It is now time for me to look in to the inpairs function. | Top |
|
The dates and times for posts above are shown in Universal Co-ordinated Time (UTC).
To show them in your local time you can join the forum, and then set the 'time correction' field in your profile to the number of hours difference between your location and UTC time.
11,316 views.
It is now over 60 days since the last post. This thread is closed.
Refresh page
top