我正在为 iPad 开发一个小项目,我只想运行一个脚本,该脚本将在某些函数调用后停止,然后让我稍后从同一个地方恢复脚本。事实上,我一次只在队列中做一个“线程”,所以它实际上只是 iPhone OS 和 Lua 之间的多任务处理。
static int yield__ (lua_State *L) {
//NSLog(@"Do Yield");
return lua_yield(L, 0);
}
//This function adds a script to my queue
- (void) doFileThreaded:(NSString*)filename {
NSString* path = [[NSBundle mainBundle] pathForResource:filename ofType:nil];
const char* file = [path UTF8String];
lua_State* newThread = lua_newthread(luaState);
//Load the file for execution
if ( luaL_loadfile(newThread,file) != 0 ) {
return;
}
//Add file to the queue
[threads addObject:[NSValue valueWithPointer:newThread]];
}
//This Function Executes the queued threads one at a time removing them when they've finished
- (void) doThreads {
lua_State* thread = NULL;
while ( threads.count > 0 ) {
thread = (lua_State*)[[threads objectAtIndex:0] pointerValue];
//Resume will run a thread until it yeilds execution
switch ( lua_resume(thread, 0) ) {
case LUA_YIELD:
//NSLog(@"Recieved Yield");
return;
case 0:
NSLog(@"Removing Thread");
[threads removeObjectAtIndex:0];
thread = NULL;
break;
default:
NSLog(@"Error Executing Threaded Script!");
[threads removeObjectAtIndex:0];
break;
}
}
}
现在对于 Lua 代码:
function wait (seconds)
time = os.time() + seconds;
print("Waiting " .. os.time() .. " to " .. time);
while ( time > os.time() ) do
yield(); --I have written my own yield function
end
end
print("Entered Toad Behavior");
yield();
print("Point 1");
yield();
print("point 3");
wait(1);
print("point 4");
wait(2);
print("point 5");
此代码将在第二次调用等待 lua 时崩溃。使用 BAD_MEMORY_ACCESS 或 lua_resume 有时会返回运行时错误。(我不知道如何检查错误是什么,所以如果你能帮助我,我也会很感激)那里的任何人都可以告诉我我在这里做错了什么吗?