2

I'm creating a lua script that should run on the TI-Nspire calculator. The problem is that while running my script I get the error Attempt to index local 'self' (a nil value) when the button:activate() method is called. The parser says the error is in the 8th line in the code below. The problematic code is as follows:

button = class(view)

function button:init()
    self.selected = false
end

function button:activate()
    self.selected = true
end

I call the activate function like this:

item = button()
local action = "activate"
local arguments = {}
item[action](unpack(arguments))

I am aware the class() function doesn't exist in "stock" Lua, it's a function available in the TI-Nspire Lua implementation. You can find its definition and usage here.

Frog
  • 1,631
  • 2
  • 17
  • 26

1 Answers1

6

obj:methodname(args) is sugar for obj.methodname(obj,args). So, if you want to use the syntax item[action](unpack(arguments)), you need to use item[action](item,unpack(arguments)). Otherwise, try item:activate(unpack(arguments)) if you can use method explicitly.

lhf
  • 70,581
  • 9
  • 108
  • 149
  • Thanks for your answer! I can't call the method explicitly, so I went with `item[action](item, unpack(arguments))`, but it doesn't fully solve my problem... Yes, the error message is gone, but it is replaced by a new one on the line that calls the method. The new error message is: `attempt to call field '?' (a nil value)`. Do you happen to now how to solve this? Thanks! – Frog Sep 08 '11 at 20:24
  • @Frog, that message indicate that `action` is not the name of a method that `item` has. Perhaps a mispelling? – lhf Sep 08 '11 at 20:56
  • Indeed, action is not the method's name, it's a string which is the method's name. I'm sure there's no typing error, because the correct function was called in my original example (which called a static method). Do you have a clue what could be wrong? Thanks! – Frog Sep 09 '11 at 09:30
  • @Frog, try `print(item,action,item[action])` before the call. – lhf Sep 09 '11 at 11:36
  • I can't use `print()` (because TI doesn't show the output, only send it to the serial port), but I have just drawer the strings to the screen instead. Variable `item` was different every time, I once had: "table: 10e77440". The `action` variable was either "activate", "mousedown", "mouseup" depending on the action and finally, `item[action]` als equaled nil. I guess this means `item[action]` isn't defined. But how is that possible when I can call `item:activate()`? – Frog Sep 09 '11 at 15:55
  • @Frog try drawing `item.activate`. Does it print "function #something", or does it print nil? – kikito Sep 13 '11 at 17:57
  • Hi Kikito! Thanks for all your replies. I've fixed the problem. Thanks! – Frog Sep 24 '11 at 20:44