Search code examples
lualove2d

Error when defining a function using a field name (`'(' expected near '['`)


I have an error of compiling with lua:

local action = {}
action["moving"] = {}
action["zooming"] = {}
action["moving"].state = false
action["zooming"].state = false

action.list = {"moving", "zooming"}

function action["moving"].f()
  if CanAction("moving") and (love.keyboard.isDown("left") or love.keyboard.isDown("right") or love.mouse.isDown("l")) then
    if action["moving"].state == false then
      action["moving"].x, action["moving"].y = camera:mousePosition()
      action["moving"].state = true
    end
    if action["moving"].state then
      if love.mouse.isDown("l") then
        camera:setPosition(-love.mouse.getX()*camera.scaleX + action["moving"].x, -love.mouse.getY()* camera.scaleY + action["moving"].y)
      elseif love.keyboard.isDown("left") then
        camera:move(-10*camera.scaleX, 0)
      elseif love.keyboard.isDown("right") then
        camera:move(10*camera.scaleX, 0)
      end
    end
  else
    ResetAction("moving")
  end
end 

The error is about the line when I declare the function "function action["moving"].f()", maybe because I use a table like that, thanks for your help.


Solution

  • You should use action["moving"].f = function() instead of function action["moving"].f() as the latter syntax is not allowed, while the former assigns an anonymous function to the field in a table.