Solarus-Games English Forum

Solarus => Development => Topic started by: lefthandedhero on June 01, 2023, 02:39:32 AM

Title: What does this error mean?
Post by: lefthandedhero on June 01, 2023, 02:39:32 AM
Recently, I created a script specifically for code related to the hero, that I called hero_meta. Here is the code that's currently in this script:

local MAX_BUFFER_SIZE = 48
function hero:on_position_changed(x,y,z)
  local hero = self
  if not hero.position_buffer then hero.position_buffer = {} end
  local hero = self
  local dir = hero:get_sprite():get_direction()
  table.insert(hero.position_buffer, 1, {x=x, y=y, layer=z, direction=dir})

  if #hero.position_buffer > MAX_BUFFER_SIZE then
    table.remove(hero.position_buffer)
  end
end


The purpose of this code is to establish a maximum distance away from the hero and create a table storing the hero's prior movements within that distance.

When I try to run the quest, I keep getting this error:
Quote
Error: In main: scripts/meta/hero_meta.lua:2: attempt to index global 'hero' (a nil value)

What does this error mean? Any idea what is causing it to occur?
Title: Re: What does this error mean?
Post by: PhoenixII54 on June 04, 2023, 10:37:05 AM
The error message says that it can't find the "hero" entity.
The reason is that you never asked the engine to give it to you in the first place.

Since you intend to make  some generic behavior for the hero -hero_meta-, you should use the hero's metatable (using sol.main.get_metatable), and then define what you need here. it works the same as using the hero directly, but more like a model, so multiples heroes will get the same behavior.
If you know the concept of object-oriented programming, then think of modifying the class instead of the instances.
Title: Re: What does this error mean?
Post by: lefthandedhero on June 05, 2023, 03:40:33 AM
Quote from: PhoenixII54 on June 04, 2023, 10:37:05 AM
The error message says that it can't find the "hero" entity.
The reason is that you never asked the engine to give it to you in the first place.

Since you intend to make  some generic behavior for the hero -hero_meta-, you should use the hero's metatable (using sol.main.get_metatable), and then define what you need here. it works the same as using the hero directly, but more like a model, so multiples heroes will get the same behavior.
If you know the concept of object-oriented programming, then think of modifying the class instead of the instances.

Thank you. This is very helpful.

I am familiar with object-oriented programming; I am a little rusty at using it since I haven't practiced using it in a few years, but I remember all the fundamental concepts.