【问题标题】:Lua and Objective C not running scriptLua 和 Objective C 没有运行脚本
【发布时间】:2010-05-25 16:32:52
【问题描述】:

我正在尝试创建一个客观的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 时搞砸了。

非常感谢任何帮助。

标题

【问题讨论】:

  • 为什么你的实例变量被声明为@public 并且还要合成它们?

标签: objective-c lua


【解决方案1】:

您的代码非常复杂,没有明显的错误。但是,您的下一步应该是检查来自lua_pcall 的返回值。如果它不为零,则堆栈顶部会出现一条错误消息,您可以通过它打印

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

如果您没有收到有用的错误消息,我的下一步是转储 Lua 堆栈。上面有多少元素?每个元素的(Lua)类型是什么?有什么价值。函数lua_topluaL_typename 将很有用。要打印该值,您必须打开lua_type 的结果。祝你好运。

【讨论】:

  • 好的,这是说 Pcall 失败:(空)。我应该从这里去哪里?
  • @beta:很莫名其妙。我的下一步是转储 Lua 堆栈。上面有多少元素?每个元素的(Lua)类型是什么?有什么价值。函数lua_topluaL_typename 将很有用。要打印该值,您必须打开lua_type 的结果。祝你好运。
【解决方案2】:

我没有运行你的代码。但是乍一看,我发现initWithScript:的签名在头文件(使用u8*)和源文件(使用s8*)之间是不同的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-30
    • 1970-01-01
    • 2015-03-01
    • 2016-06-19
    • 2015-08-30
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多