Page 1 of 1

[solved] "game is nil" in on_load method

Posted: Wed Aug 24, 2016 8:10 pm
by nakran
Here's the thing, I have an on_load method implemented where I retrieve the player (singleplayer mode) and it fails when I use the local variable of the following line:

local lplayer = game.player

What I don't understand is WHY this works for a new game but not for a saved one. What's happening here with the "game"?
If anyone wants the context: I'm trying to make a "test mod" where I clean every inventory slot when a new world is generated. I'm doing it in the on_load method because the on_init method seems to not like the 'player' field of 'game' (so I've setup a global var to know if it is a new game)

Code below:

Code: Select all

script:on_init(function(event)
    global.empty_inventories = true
end)

script:on_load(function(event)
    if global.empty_inventories == nil then
         global.empty_inventories = true

    if global.empty_inventories == true then
        local lplayer = game.player
        for i,6,1 do
            lplayer.get_inventory(i).clear()
        end
    end
end)
Thanks in advance!

Re: "game is nil" in on_load method

Posted: Wed Aug 24, 2016 9:11 pm
by Supercheese
  1. You shouldn't use on_load for that, on_init should be just fine...
  2. ... because you shouldn't use game.player, instead game.players[1] if you're only supporting singleplayer, or loop over pairs(game.players) if you want to support multiplayer.

Re: "game is nil" in on_load method

Posted: Wed Aug 24, 2016 9:14 pm
by Nexela
nakran wrote:If anyone wants the context: I'm trying to make a "test mod" where I clean every inventory slot when a new world is generated. I'm doing it in the on_load method because the on_init method seems to not like the 'player' field of 'game' (so I've setup a global var to know if it is a new game)
In a new game there is no player in game. until after on_player_created. if you add the mod to an existing game with existing players then game.players[] won't be nil
nakran wrote:Here's the thing, I have an on_load method implemented where I retrieve the player (singleplayer mode) and it fails when I use the local variable of the following line:
local lplayer = game.player
game. is nil in onload by design

So what you want is on_player_created or on_player_joined events- both of these are called once in single player when a player is created or joins (join is only called once in singleplayer regardless if you reload the map since your player has already joined the map)

and to top it off game.player is nil if not sent from the console (I think)

So pseudo code ->

on_player_created event
player = game.players[event.player_index]
--Do inventory code here on player object

Re: "game is nil" in on_load method

Posted: Wed Aug 24, 2016 9:16 pm
by nakran
Woah. Thank you very much for the answers and for your time :)
That fixed my problems!