Lua和一点多任务处理

我正在为iPad开展一个小项目,我只想运行一个脚本,该脚本将在某些函数调用后停止,然后让我稍后从同一位置恢复脚本。实际上,我只在队列中一次执行一个'threads',因此在iPhone OS和Lua之间实际上只是多任务处理。

现在是Lua代码:

该代码将在第二次调用等待时在lua上崩溃。使用BAD_MEMORY_ACCESS或lua_resume有时会返回运行时错误。(我不知道如何检查错误,所以如果你能帮助我,我将不胜感激)是否有人可以告诉我我在这里做错了什么?

原文链接 https://stackoverflow.com/questions/2971943

点赞
stackoverflow用户358167
stackoverflow用户358167

好的,我并不能百分之百地理解,但我认为这与我从另一个正在执行的 Lua 脚本中调用 doFileThreaded 有关。看起来,尽管 lua_State 不同,但我从已经被 Lua 调用的函数中调用了 luaL_loadfile,这仍然会导致“attempt to yield across metamethod/C-call boundary”。

我的解决方案是将我想要运行的文件名保存为字符串,然后在 doThread 中调用 lua_newthread。

- (void) doFileThreaded:(NSString*)filename {

NSString* path = [[NSBundle mainBundle] pathForResource:filename ofType:nil];

//Add to queue
[threads addObject:path];
}

- (void) doThreads {

//Will run through the threads in the order they've been queued.
//Cooperative Multitasking

while ( threads.count > 0 ) {

    //If there is no thread start one
    if ( threadState == NULL ) {

        threadState = lua_newthread(luaState);

        const char* file = [[threads objectAtIndex:0] UTF8String];

        if ( luaL_loadfile(threadState,file) != 0 ) {
            NSLog(@"%s\n", lua_tostring(threadState,-1));
            [threads removeObjectAtIndex:0];
            threadState = NULL;
            return;
        }

        //Return because we don't want to resume the file right away
        //return;

    }

    //Resume will run a thread until it yeilds execution
    switch ( lua_resume(threadState, 0) ) {
        case LUA_YIELD:
            return;

        case 0:
            //New Thread
            NSLog(@"Thread Returned");
            threadState = NULL;
            [threads removeObjectAtIndex:0];
            break;

        case LUA_ERRMEM:
            NSLog(@"LUA_ERRMEM");
            NSLog(@"%s\n", lua_tostring(threadState,-1));
            [threads removeObjectAtIndex:0];
            break;

        case LUA_ERRERR:
            NSLog(@"LUA_ERRERR: error while running the error handler function");
            NSLog(@"%s\n", lua_tostring(threadState,-1));
            [threads removeObjectAtIndex:0];
            break;

        case LUA_ERRRUN:
            NSLog(@"LUA_ERRRUN: a runtime error.");
            NSLog(@"%s\n", lua_tostring(threadState,-1));
            [threads removeObjectAtIndex:0];
            break;

        default:
            NSLog(@"Error Executing Threaded Script!");
            NSLog(@"%s\n", lua_tostring(threadState,-1));
            [threads removeObjectAtIndex:0];
            break;

    }

}

}

Whew 这真是个令人头疼的问题。但它现在可以工作了!

2010-06-04 07:36:22