user112016322
user112016322

Reputation: 698

How to use OO in Lua Corona Labs? Unable to index error

Im using the Corona SDK for developing games and created a new project that comes with a main.lua file, but wanted to add other seperate files such as player.lua so i could do object oriented.

My goal is to create a player from the main and i did some research on how that can be done.
a link to lua tutorial

Here is my code for those files:

player.lua :

Player = {}

Player.new = function(name, id)

    local self = {}
    name = name or "player"
    id = id or 0

    self.getName = function() return name end
    self.getId = function() return id end

    end
return self

main.lua :

local Player = require("scripts.player")

player1 = Player.new("Player1", 1)
print(player1.getName())

Im expecting a print in the console. The error says 'unable to index local Player (a boolean value) stack traceback' in main.lua

Upvotes: 0

Views: 119

Answers (2)

Aki
Aki

Reputation: 2938

The first issue is that you have the return statement for constructor in the wrong place. It should be inside the constructor rather than outside:

Player = {}

Player.new = function(name, id)
    local self = {}
    name = name or "player"
    id = id or 0

    self.getName = function() return name end
    self.getId = function() return id end

    return self
end

Indenting your code consistently will help you see such problems straight away. I suggest always having end indented at the same level as the opening of the block (no matter if it is a function, for, do or whatever else).

After solving this issue you have the problem mentioned by Nifim - you need to take care of shadowing the Player. The simplest solution would be to add a return statement in the end of the player.lua:

Player = {}

-- `Player.new` and so on...

return Player

You could also make the Player local if you want. It is not needed but it might be desired.

Or you could remove the assignment from the main.lua:

require("scripts.player")
local player = Player.new()

Upvotes: 1

Nifim
Nifim

Reputation: 5021

You do not return your player lib in player.lua. so when you call

local Player = require("scripts.player")

You shade the global variable Player created in player.lua with the result of require which is true.

References on Require: https://www.lua.org/manual/5.3/manual.html#6.3


You have 2 choices to correct this issue.

Option 1) change player.lua

local Player = {}

Player.new = function(name, id)

    local self = {}
    name = name or "player"
    id = id or 0

    self.getName = function() return name end
    self.getId = function() return id end

    return self
end

return Player

OR Option 2) Change main.lua

require("scripts.player")

player1 = Player.new("Player1", 1)
print(player1.getName())

Option one follows more modern Lua module conventions, but either option will resolve your issue.

Upvotes: 3

Related Questions