【问题标题】:Control flow in LuaLua 中的控制流
【发布时间】:2012-06-25 15:06:47
【问题描述】:

我有一个问题,我想这一定很常见,你们中的大多数人都会遇到它。 我在 lua 中编写了一个程序,比如 main.lua,它在接收到关键事件时应该修改坐标并显示几何图形。 此 lua 代码调用 reg.c,它在其中进行注册。 现在在 reg.c 我有一个函数引擎,它接收按下的键并将其传递给负责键处理的 lua 函数。 但是当key事件到来时,lua代码完成注册并退出,因此来自engine()的调用变成了非法的内存访问,导致分段错误。

另外我想我们不能让 lua 调用挂在 reg 函数中,并从其他地方调用引擎函数。

那应该怎么解决,请指导我。


@jacob:这是我想要实现的原型:

function key_handler() //this function will get the latest key pressed from some other function
{
     draw.image();
     draw.geometry();
     ...
     ...

     while(1)
     {
         //draw Points until some condition goes wrong      
     }

}

现在,一旦进入 key_handler,当他忙于绘制点时,除非并且直到出现故障情况,我才能收到按键。

我希望这个解释更简单,并表达了我的观点,并有助于其他人理解这个问题。 我真的很抱歉,但我不擅长表达或让别人理解。

还有一点,我一直按照C的语法来解释,不过这完全是用lua实现的

【问题讨论】:

  • 很难从你的问题中看到你的设置和你想要完成的事情(例如,没有人知道reg.c 做什么或应该做什么,engine() 也是如此)。请详细说明,并给出一个最小的代码示例来演示什么不起作用。
  • @jpjacobs : 我已经尽我最大的努力更新了这个问题,请看看你是否可以推荐我一些解决问题的方法
  • 我尝试过使用协程,但没有帮助
  • @jpjacobs 我已经尽我所能更新了这个问题,请看看你是否可以推荐我一些解决问题的方法

标签: lua embedded-linux lua-5.2


【解决方案1】:

您的代码 sn-p 在很大程度上仍然没有提供信息(理想情况下,应该能够在普通的 Lua 解释器中运行您的代码并查看您的问题)。如果您要描述 Lua 问题,请使用 Lua 代码来描述它。

但是我开始知道你想去哪里了。

您需要做的就是在您的密钥处理程序中调用一个协程,它将一个参数传回您的处理程序:

function isContinue() --just to simulate whatever function you use getting keypresses.
-- in whatever framework you're using there will probably be a function key_pressed or the like.
    print('Initialize checking function')
    while true do
        print('Continue looping?')
        local ans = io.read():match('[yY]')
        local action
        if not ans then
            print('Do what instead?')
            action = io.read()
            if action:match('kill') then -- abort keychecker.
                break
            end
        end
        coroutine.yield(ans,action)
    end
    print('finalizing isContinue')
    return nil,'STOP' -- important to tell key_handler to quit too, else it'll be calling a dead coroutine.
end

function key_handler()
    local coro = coroutine.create(isContinue)
    local stat,cont,action
    while true do
        print'Draw point'
        stat,cont,action = coroutine.resume(coro)
        if not stat then
            print('Coroutine errored:',cont)
        elseif not cont then
            print('isContinue interrupted keyhandler')
            print("We'll "..action.." instead.")
            break
        end
    end
    print('finalizing key_handler')
end

key_handler()
-- type something containing y or Y to continue, all else aborts.
-- when aborting, you get asked what to do instead of continuing, 
--- with "kill" being a special case.

这应该是不言自明的。你应该好好看看Programming in Lua, chapter 9: Coroutines

最大的困难(好吧,如果你不习惯协作线程的话)是协程应该让自己产生:它不是负责返回控制的调用函数。

希望对你有所帮助。

【讨论】:

    猜你喜欢
    • 2020-03-12
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    • 2015-09-29
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    • 2020-06-07
    相关资源
    最近更新 更多