2012-06-25 29 views
0

我有一個問題,我認爲這個問題一定很常見,而且大多數人都會遇到它。 我已經寫了一個程序在lua中說main.lua在接收關鍵事件時應該修改座標並顯示幾何圖形。 這個lua代碼調用reg.c,在那裏註冊。 現在在reg.c中我有一個函數引擎,它接收按鍵並將它傳遞給負責密鑰處理的lua函數。 但是到了關鍵事件發生的時候,lua代碼就完成了註冊並退出,這樣來自engine()的調用就成爲非法的內存訪問,導致了分段錯誤。Lua中的控制流程

另外我想我們不能讓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,而他正忙,除非和直到發生故障的情況發生時繪製點,直到那個時候,我無法收到按鍵。

我希望這個解釋更加簡單,並且提出了我的觀點,並且會幫助他人理解問題。 我真的很抱歉,但我不善於表達或讓別人理解。

還有一兩件事,我ahve遵循C語法來解釋,但是這是在盧阿完全實現

+0

很難看到你的設置以及你想從你的問題中完成什麼(例如,沒有人知道'reg.c'做了什麼或者應該做什麼,'engine()'也是如此)。請詳細說明,並給出一個最低限度的代碼示例來演示什麼不起作用。 – jpjacobs

+0

@jpjacobs: 我已經更新了這個問題,盡我所能,好心的看你是否可以推薦我解決一些問題 – ashutosh

+0

我試過使用協程,但沒有幫助 – ashutosh

回答

0

你的代碼片段在很大程度上仍是無信息的(理想情況下應該能夠公正運行代碼的股票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

如果你不習慣於協作線程,那麼很大的困難就是協程應該讓步:它不是負責返回控制的調用函數。

希望這可以幫助你。