Archived

This topic is now archived and is closed to further replies.

Lua Statics?

This topic is 4954 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

The classic way is to use closures.


do
local currentcount = 0 -- defines local variable in the do..end scope, and initializes it
function counter()
currentcount = currentcount+1 -- uses the value as a closure, so its value is saved
return currentcount
end
end

print(counter()) -- prints ''1''
print(counter()) -- prints ''2''

Personally, I don''t do that much. To me, static variables imply that I don''t actually want a function at all, but rather an object. Here''s how I''d make a counter:

function newcounter()
return {
currentcount = 0,
next = function(self)
self.currentcount = self.currentcount + 1
return self.currentcount
end
}
end

counter = newcounter()
print(counter:next())
print(counter:next())

Ultimately, it''s mostly a matter of personal preference.



"Sneftel is correct, if rather vulgar." --Flarelocke

Share this post


Link to post
Share on other sites