Advertisement

Lua Statics?

Started by May 20, 2004 03:08 PM
1 comment, last by nickwinters 20 years, 3 months 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
Global variables? In fact all variables are global by default,
unless you specify "local".


Kami no Itte ga ore ni zettai naru!
神はサイコロを振らない!
Advertisement
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