Re: Weird numeric for loop counter variable behavior

  • From: Cheyi Lin <cheyi.lin@xxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Fri, 7 Mar 2014 15:26:32 +0800

Thanks for the replies,

Sorry about lack of related context, here it is, foo.lua and main.lua.

'Foo' is an simple event emitter module, you push a handler function,
register an event with callback and wait for be triggered.
The problem I posted is the handler function in main.lua.

I embedded LuaJIT 2.0.2 (git e3d5b21) in C, an event-driven server
application, with a 'tick' timer that invokes a top level Lua function
periodically to processing queued events one by one.

I'm still digging the possible logical bugs, if you need any
information please let me know, thanks.

Regards,
Cheyi


-- [ foo.lua ]

local setmetatable = setmetatable
local type = type
local table = table

local Foo = {}

function Foo:new()
  local obj = {
    handler_stack = {},
    event_map = {},
  }
  setmetatable(obj, self)
  self.__index = self
  return obj
end

function Foo:push_handler(handler)
  if type(handler) == "function" then
    table.insert(self.handler_stack, handler)
  end
end

function Foo:pop_handler(handler)
  return table.remove(self.handler_stack)
end

function Foo:register_event(event_id, event_cb)
  if type(event_cb) == "function" then
    self.event_map[event_id] = event_cb
  end
end

function Foo:trigger_event(event_id)
  local event_cb = self.event_map[event_id]
  if event_cb then
    self.event_map[event_id] = nil
    event_cb(self)
  end
end

return Foo

-- end of foo.lua

-- [ main.lua ]

local Foo = require("foo")
local N = 4

foo = Foo:new()
bar =
  function (foo, i)
    -- do something irrelevant
  end

foo:push_handler(
  function ()
    for i = 1, N do  -- // PROBLEM HERE //
      print(i)
      bar(foo, i)
    end
  end)

foo:register_event("my_event",
  function ()
    local h = foo:pop_handler()
    if h then h() end
  end)

foo:trigger_event("my_event")

-- end of main.lua

Other related posts: