123iamking
123iamking

Reputation: 2703

Lua - Why don't Global variables need declarations?

According to Lua's manual

Global variables do not need declarations. You simply assign a value to a global variable to create it. It is not an error to access a non-initialized variable; you just get the special value nil as the result

I think declaration is good, it makes thing more manageable. Why did Lua skip declarations for Global variables? I guess they have a good reason but I don't know why.

What if I make this mistake

-- Activation Code
function TestLoco:OnActivate()
    self.MyGlobal = "ABC"; --Init the global variable
end

-- Run every tick
function TestLoco:OnTick()
    self.MyGIobaI = "BCD"; --Edit the global variable at every tick, but I mistake 'I' with 'l'
end

-- Call when I click the mouse
function TestLoco:OnClick()
    Debug.Log(self.MyGlobal); --This print "ABC", but It should be "BCD", what if I don't notice this?
end

Upvotes: 1

Views: 1468

Answers (1)

IS4
IS4

Reputation: 13207

Because Lua has no classes. self.MyGlobal is not a global variable, it is a field in the table passed via the self parameter. The syntax is equivalent to self["MyGlobal"]. For a "true" global variable assignment (e.g. x = 0), it is equivalent to _G["x"] = 0, where _G is the global environment table.

Since Lua has no notion of classes, the type of self is simply a table. The syntax you use for specifying a "method" is just a syntactic shortcut to this:

TestLoco.OnActivate = function(self)
    self["MyGlobal"] = "ABC";
end

It's just a function that assigns a field in a table. It could be called with potentially any table, hence it cannot verify the table actually should have that field.

However, Lua offers some pretty good run-time customisable checking via metatables. If you build a table specifying the "class" of a table, you can assign a metatable to every table that checks the assignment each time if it assigns to a field that you actually "declared".

Upvotes: 1

Related Questions