Lua和Objective C无法运行脚本。

Objective C 接口封装lua脚本的功能,包括存储和运行脚本(编译过或未编译过)。脚本接口的代码如下所示:

< #import <Cocoa/Cocoa.h>
#import "Types.h"
#import "lua.h"
#include "lualib.h"
#include "lauxlib.h" # >

@interface Script : NSObject<NSCoding> {
@public
  s32 size;
  s8* data;
  BOOL done;
}

@property s32 size;
@property s8* data;
@property BOOL done;

- (id) initWithScript: (u8*)data andSize:(s32)size;
- (id) initFromFile: (const char*)file;
- (void) runWithState: (lua_State*)state;
- (void) encodeWithCoder: (NSCoder*)coder;
- (id) initWithCoder: (NSCoder*)coder;

@end

#import "Script.h"

@implementation Script

@synthesize size;
@synthesize data;
@synthesize done;

- (id) initWithScript: (s8*)d andSize:(s32)s
{
        self = [super init];
 self->size = s;
 self->data = d;
 return self;
}

- (id) initFromFile:(const char *)file
{
        FILE* p;
     p = fopen(file, "rb");
     if(p == NULL) return [super init];
      fseek(p, 0, SEEK_END);
        s32 fs = ftell(p);
     rewind(p);
     u8* buffer = (u8*)malloc(fs);
     fread(buffer, 1, fs, p);
      fclose(p);

     return [self initWithScript:buffer andSize:size];
}

 - (void) runWithState: (lua_State*)state
 {
  if(luaL_loadbuffer(state, [self data], [self size], "Script") != 0)
  {
   NSLog(@"Error loading lua chunk.");
   return;
  }
  lua_pcall(state, 0, LUA_MULTRET, 0);

}

- (void) encodeWithCoder: (NSCoder*)coder
{
  [coder encodeInt: size forKey: @"Script.size"];
 [coder encodeBytes:data length:size forKey:@"Script.data"];
}

- (id) initWithCoder: (NSCoder*)coder
{
 self = [super init];
 NSUInteger actualSize;
 size = [coder decodeIntForKey: @"Script.size"];
 data = [[coder decodeBytesForKey:@"Script.data" returnedLength:&actualSize] retain];
 return self;
}

@end

这是主方法:

#import "Script.h"

int main(int argc, char* argv[])
{
 Script* script = [[Script alloc] initFromFile:"./test.lua"];
 lua_State* state = luaL_newstate();
 luaL_openlibs(state);
 luaL_dostring(state, "print(_VERSION)");
 [script runWithState:state];
 luaL_dostring(state, "print(_VERSION)");
 lua_close(state);
}

lua脚本如下: print("O Hai World!")

加载文件正确,但我认为它在pcall中出错了。

非常感谢任何帮助。

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

点赞
stackoverflow用户41661
stackoverflow用户41661

你的代码非常复杂,没有明显的错误。然而,你的下一步应该是检查从 lua_pcall 返回的值。如果它不为零,栈顶上将有一个错误消息,你可以通过以下方式打印:

fprintf(stderr, "Pcall failed: %s\n", lua_tostring(state, -1));

如果你没有得到有用的错误消息,我的下一步将是转储 Lua 栈。栈上有多少元素?每个元素的(Lua)类型是什么?它的值是什么?函数 lua_topluaL_typename 将非常有用。要打印值,你必须根据 lua_type 的结果进行切换。祝你好运。

2010-05-25 17:16:02
stackoverflow用户124820
stackoverflow用户124820

我没有运行你的代码。但乍一看,我发现 initWithScript: 的签名在头文件中使用 u8*,而在源文件中使用 s8*

2010-05-26 04:58:16