Archived

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

nickwinters

Lua Statics?

Recommended Posts

I''ve finally realized that there are no static variables in Lua. So is there an alternative in Lua that works similar to statics? Thanks. -Nick

Share this post


Link to post
Share on other sites
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