Page 1 of 1

Help with "require" needed

Posted: Wed Oct 17, 2012 8:36 am
by Ser_Mitch
Hey guys,

I'm new to Love and Lua and all this, so please don't be mad if this is a noobish question...

I'm having trouble with the 'require' module... I want to require player.lua in main.lua. I think i have done it the same as i have seen in the official lua documentation and in other examples, mainly from these forums, but all i get is the error message:

Error

player.lua:3 attempt to index global 'player' (a nil value)

Traceback

player.lua:3 in main chunk
[C]: in function 'require'
main.lua:3 in main chunk
[C]: in function 'require'
[C]: in function 'xpcall'

(what does all this mean?)

I have looked through these forums, and the rest of the internet, but i cant seem to find what im doing wrong...

Someone help please :s

Re: Help with "require" needed

Posted: Wed Oct 17, 2012 8:52 am
by Roland_Yonaba
Well, the problem is not with require.
Lua says there is an error in player.lua, at line 3, so require cannot load this file.
In player.lua, define player as a local table first, before adding functions inside. Then return this table later on.

Code: Select all

-- at the top of player.lua
local player = {}
-- same as before, but obviously, remove line 8 in player.load() (i.e player = {})
-- at the bottom of player.lua
return player
That should fix the problem, but require will still err, I guess, because inside player.update() function, game is an undefined variable. But that's not really my call.

Re: Help with "require" needed

Posted: Wed Oct 17, 2012 8:57 am
by Ser_Mitch
Thank you so much, it all works now :D But even better, I understand why :)

Re: Help with "require" needed

Posted: Wed Oct 17, 2012 8:59 am
by Nixola
The require works fine, the problem is in player.lua. Do you know how tables work?
When you write "function player.load()" you are telling LÖVE to "grab" the table named "player" and put a function in its "load" field. The problem is you didn't ever create that table, you should write "player = {}" on top of your player.lua, or inside main.lua before requiring player.lua. I recommend the former, though.

EDIT: Aw, too slow >.<
Anyway, Roland's right, the table should be local ("local player = {}") and it should be returned at the end of the file ("return player")

EDIT #2: Awfully slow. T.T

Re: Help with "require" needed

Posted: Wed Oct 17, 2012 9:04 am
by Ser_Mitch
All good nixola.. Thanks guys, I wasn't actually expecting to get an answer back so quick :P

Re: Help with "require" needed

Posted: Wed Oct 17, 2012 9:09 am
by Roland_Yonaba
Obey...Khal Drogo...

Re: Help with "require" needed

Posted: Wed Oct 17, 2012 10:15 am
by kikito
Roland_Yonaba wrote:Obey...Khal Drogo...
It is known.