Home > Software design >  Arguments not properly passed to function
Arguments not properly passed to function

Time:12-25

I am new to Lua, and I downloaded and wanted to use the class.lua file from this link. However, when I attempt to call the Board:addSign function from anywhere, no matter what I do, the arguments passed are the value of the place variable and nil instead of the values of the sign and place variables. How would I go around fixing that?

Here's my code, both main and the class itself.

Class = require 'class'
require 'Board'

board = Board()

for place = 1, 9 do
  print('Input sign: ')
  sign = io.read()
  board.addSign(sign, place)
end
Board = Class{}

function Board:init()
  array = {}
  for n = 1, 9 do
    array[n] = ' '
  end
  --
  self.array = array
end

function Board:addSign(sign, place)
  print(sign) -- outputs whatever I passed as place
  print(place) -- outputs nil no matter what
  self.array[place] = sign -- crashes here since place is nil
end

CodePudding user response:

Use board:addSign instead of board.addSign.

CodePudding user response:

function Board:addSign(sign, place) end

is syntactic sugar for

function Board.addSign(self, sign, place) end

This allows you to do things like self.array[place] = sign inside that function.

So you defined a function with 3 parameters but you only provide 2 when calling it.

board.addSign(sign, place)

Inside your function that basically results in

local self = sign
local sign = place
local place = nil

So either call Board:addSign(sign, place) or Board.addSign(Board, sign, place)

  • Related