🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

Lua Statics?

Started by
1 comment, last by nickwinters 20 years, 1 month ago
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
Advertisement
Global variables? In fact all variables are global by default,
unless you specify "local".


Kami no Itte ga ore ni zettai naru!
神はサイコロを振らない!
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    endendprint(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    }endcounter = newcounter()print(counter:next())print(counter:next())

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


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

This topic is closed to new replies.

Advertisement