Table with function that uses the table's other fields
0 replies, posted
So, the wiki's down, therefore I'm forced to ask this before searching in it:
Basically I have a table with some fields in it:
[lua] newskill = {
name=oldskill.name,
level=oldskill.level,
exp=oldskill.exp,
update= function() ...
}[/lua]
I want the update function to be able to access the newskill.level and newskill.exp values. How can I proceed?
[editline]26th January 2012[/editline]
Wandering around the forum I just found this:
[URL="http://maurits.tv/data/garrysmod/wiki/wiki.garrysmod.com/index4875.html?title=Main_Page"]http://maurits.tv/data/garrysmod/wiki/wiki.garrysmod.com/index4875.html?title=Main_Page[/URL]
Usefull ^^
[editline]26th January 2012[/editline]
Found the answer to my question by R-ing-TFM:
[URL="http://www.lua.org/pil/16.html"]http://www.lua.org/pil/16.html[/URL]
Objects have their own operations. Tables also can have operations:
[lua]Account = {balance = 0}
function Account.withdraw (v)
Account.balance = Account.balance - v
end[/lua]
This definition creates a new function and stores it in field withdraw of the Account object. Then, we can call it as
[lua]Account.withdraw(100.00)
[/lua]
So in the end:
[lua]newskill = {
name=oldskill.name,
level=oldskill.level,
exp=oldskill.exp,
}
newskill.update = function()
if newskill.exp > newskill.level*100 then
newskill.level=newskill.level+1
newskill.exp=0
end
end[/lua]
Sorry, you need to Log In to post a reply to this thread.