For a game using CoronaSDK I'm trying to implement some OOP in Lua.
If I run the following code in the Corona simulator:
-- Terrain Sprites base
local TerrBase = {}
local TerrBase_mt = {_index = TerrBase}
function TerrGrass_mt.baseAdd(a,b)
print(a+b)
end
-- Terrain Sprites - Grass
local TerrGrass = {}
function TerrGrass.new()
local grass = {}
setmetatable(grass,TerrBase_mt)
return grass
end
function TerrGrass.add(a,b)
print(a+b)
end
function TerrGrass.sub(a,b)
print(a-b)
end
function TerrGrass.mul(a,b)
print(a*b)
end
function TerrGrass.div(a,b)
print(a/b)
end
--
local grass = TerrGrass.new()
grass.add(5,7)
I get this message:
What is the reason for this error?
local TerrBase = {}
local TerrBase_mt = {_index = TerrBase}
function TerrGrass_mt.baseAdd(a,b) -- <---- ERROR
print(a+b)
end
You're attempting to index a table named TerrGrass_mt
. But the table you defined is named TerrBase_mt
.
TerrGrass_mt
is a nil
value, hence the error.
Let's have a look at the error message:
main.lua 12: attempt to index global 'TerrGrass_mt' (a nil value).
This tells you that the error occured in line 12 of the file main.lua.
You attempted to index (use the index operator .
) on a global named TerrGrass_mt. This tells you that the problem is is TerrGrass_mt.
and that TerrGrass_mt
is nil.
Something like
function a(b) c = b.d end
a()
would give you an error for indexing a local nil value b
because here b's scope is local.
Whenever you get an error for using nil values in any way you have to find out why the value is nil and either fix that or in some cases replace it with a default value.