Error in Lua code

Post Reply
User avatar
Monika_Miyazaki
Member
Posts: 28
Joined: Sun Sep 22, 2019 17:21
In-game: Monika_Miyazaki
Location: Moscow, Russia

Error in Lua code

by Monika_Miyazaki » Post

Error attempt to index field 'player' (a nil value) in mod for CSM.

The error occurs because the code cannot initialize the player.

Code: Select all

local player = minetest.localplayer
How do I initialize a player without making error?
Reception: We need it to work for CSM Mod.
Just Monika!

zing269
Member
Posts: 109
Joined: Sat Apr 30, 2016 19:10

Re: Error in Lua code

by zing269 » Post

CSMs load before the player exists in the world so you will need to make sure that you have a reference to the player before you try to use it.

This code will NOT work

Code: Select all

local player = minetest.localplayer

local function dostuff ( something )
  ...
  local pos = player:get_pos()
  --error occurs player not defined 
This code will work

Code: Select all

local player = minetest.localplayer

local function dostuff ( something )
  ...
  -- make sure we have a reference to player
   if not player and not minetest.localplayer then
      return
   elseif not player then
      player = minetest.localplayer
   end

  local pos = player:get_pos()

User avatar
Monika_Miyazaki
Member
Posts: 28
Joined: Sun Sep 22, 2019 17:21
In-game: Monika_Miyazaki
Location: Moscow, Russia

Re: Error in Lua code

by Monika_Miyazaki » Post

zing269 wrote:CSMs load before the player exists in the world so you will need to make sure that you have a reference to the player before you try to use it.
Thank you for the explanation. This information should help get rid of the current problem.
And thank you for setting a good example.
Just Monika!

User avatar
Monika_Miyazaki
Member
Posts: 28
Joined: Sun Sep 22, 2019 17:21
In-game: Monika_Miyazaki
Location: Moscow, Russia

Re: Error in Lua code

by Monika_Miyazaki » Post

zing269 wrote: This code will work

Code: Select all

local player = minetest.localplayer

local function dostuff ( something )
  ...
  -- make sure we have a reference to player
   if not player and not minetest.localplayer then
      return
   elseif not player then
      player = minetest.localplayer
   end

  local pos = player:get_pos()
Yes. This code helped to solve the problem with initialization of the player.
Just Monika!

zing269
Member
Posts: 109
Joined: Sat Apr 30, 2016 19:10

Re: Error in Lua code

by zing269 » Post

Glad to be of help.

There are other issues with CSM, not too surprising given it's stage of development. I've also run into problems with storage, perhaps it was a similar issue of timing, or perhaps the engine is looking in /mods instead of /clientmods, I was only playing around with CSM and decided to wait for it to mature some rather than trying to find the real problem.

Post Reply

Who is online

Users browsing this forum: No registered users and 4 guests