Reputation: 111
I have a file, display.lua in which I have code to load some resources.
----display.lua
Resources = {}
function Resources:new(rootdir)
local newObj = {image = {}, audio = {}, root = ""}
newObj.root = rootdir
return setmetatable(newObj, self)
end
function Resources:getSpriteSheet(name)
--- etc etc etc
end
and then I have a game variable I use to store gamestate, this is within another file game.lua.
---game.lua
require "display.lua"
function Game:new()
local newObj = {mode = "", map = {}, player = {}, resources = {}}
self.__index = self
return setmetatable(newObj, self)
end
function Game:init()
self.resources = Resources:new("/home/example/etc/game/")
local spriteSheet = self.resources:getSpriteSheet("spritesheet.png")
end
I have access to the resources code via use of require
. My issue is that within Game:init()
I can't access Resources:getSpriteSheet()
, the lua interpreter complains of "attempt to call method (getSpriteSheet) a nil value"
I assume here I would have to export the methods in Resources but I don't know how I'd go about doing this, as I'm quite new to Lua.
Upvotes: 5
Views: 9310
Reputation: 26754
I think you want return setmetatable(newObj, {__index = self})
instead of return setmetatable(newObj, self)
.
Also, require "display.lua"
should probably be require "display"
and game.lua
should have Game = {}
somewhere at the top. With these changes your example works for me.
Upvotes: 3