Table update variable (SOLVED)

I have a table with some text that I use as instructions (lua module). So depending on the progress of the player my gui script will choose a specific text instruction from my table. One of the text includes a variable from another lua module. But it seems like my variable stay 0 when I update the variable and set the text of the node.

Example:

local player = require("lib.player")

local M = {}

M.INSTRUCTIONS =
{
  --tutorial
  {text = "Instruction 1"},
  {text = "Instruction 2"},
  {text = "Instruction 3"},

  --game
  {text = "Tap to Start!"},
  {text = "Try to beat your Highscore:\n" .. player.highscore_ref}
}

return M

When I update the player.highscore_ref variable and set the text, the text always gives me player.highscore_ref variable as 0. Why is this?

So it will always be:

Try to beat your Highscore: 0

Hi!

Since M.INSTRUCTION is evaluated/created once, the current value for player.highscore_ref at that time is what will be concatenated to the string.

You could instead make it a function, something like:

M.INSTRUCTIONS = {}
M.update_instructions = function(self)
   self.INSTRUCTIONS =
   {
     --tutorial
     {text = "Instruction 1"},
     {text = "Instruction 2"},
     {text = "Instruction 3"},

     --game
     {text = "Tap to Start!"},
     {text = "Try to beat your Highscore:\n" .. player.highscore_ref}
   }
end

Then run it after each time you update the highscore, or just before you need the data. Something like this:

player.highscore_ref = 1337
M:update_instructions()
print(M.INSTRUCTIONS[5])
-- Should print this:
-- "Try to beat your Highscore:\n1337"
5 Likes

Okay but what about if I want to call for example index 1 instead of 5 how would I go about doing that because I’m getting:

attempt to index a nil value

This is what I have in my gui script:

local gui_M = require("lib.gui")

gui_M.update_instructions (self)
gui.set_text(self.instruction, gui_M.INSTRUCTIONS[player.tip_stage].text)

EDIT:

I see that it should be:

gui_M:update_instructions ()

Instead of:

gui_M.update_instructions (self)

Yes,
which is a shorthand in Lua for doing this:

gui_M.update_instructions(gui_M)
3 Likes