How to export then access exported methods in Lua

I have a file, display.lua, in which I have the 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 that I am using to store the game gamestate, this is in another game.lua file.

---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 resource code using require

. My problem is that in Game:init()

I cannot access Resources:getSpriteSheet()

, the lua interpreter is complaining about "trying to call the method (getSpriteSheet) value nil"

I suppose I would have to export the methods to Resources, but I don't know how I would do that as I am completely new to Lua.

+3


source to share


1 answer


I think you want return setmetatable(newObj, {__index = self})

instead return setmetatable(newObj, self)

.



In addition, there require "display.lua"

should be require "display"

, but game.lua

should have Game = {}

somewhere on top. With these changes, your example works for me.

+2


source







All Articles