Main Content

Automatically initialising Lua variables the first time

Archive - Originally posted on "The Horse's Mouth" - 2009-08-10 18:30:50 - Graham Ellis

In Lua, you need to initialise variables before you perform arithmetic on them, but you CAN test them (and if they don't exist, they will return false).

For example, this code initialises a variable to 0 if it doesn't exist, or takes its current value, then adds 1 to it straight away before saving it tack in the same variable.

callcounter = (callcounter or 0 ) +1

See that in use in full source code, within a function where it in effect becomes a static variable , here