Jump to content
  • Advertisement

Archived

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

nickwinters

Lua Statics?

This topic is 5236 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

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
Advertisement
Global variables? In fact all variables are global by default,
unless you specify "local".



Kami no Itte ga ore ni zettai naru!

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

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!