OC与Lua调用交互(不使用第三方库)

研究这块东西的起因

既不是为了当成游戏里的脚本用;也不是为了用lua调用原生控件实现跨平台;只是为了保持和我司Android端的部分关键算法一致,所以把这部分代码写成了lua。

起初查资料,会有wax、cocos2d之类的内容,但是我们并需要这么“重量级”的东西,就一个lua文件,所以最后决定用C和lua交互,自己写。

目前这部分东西已经在线上跑了1年+,至少是可以用的。

分享一部分有关键代码和最初开发思路。

达到目标

1.正确传参

  • 基础数据格式:BOOL、Number、NSString
  • NSArray、NSDictonary等复杂参数传入

2.实现返回数据

  • 基础数据格式:BOOL、Number、NSString
  • NSArray、NSDictonary等复杂参数返回值

添加Lua

下载Lua,将src目录改名为lua,拖进项目。删除掉lua.c和luac.c

这个时候编译是成功的。

我使用的版本是Lua 5.1.4,当初为了与安卓团队的第三方jar包版本保持一致。新版本应该语法有一些改变。

Lua这边有用的东西

这是我在调试lua的table用的print,因为会用到时间戳,所以有个地方判断了数字,lua里的print是不能输出table的格式,可比NSLog不方便多了。于是在网上搜索了下资料,最后对应我们自己的需求做了一点点调整,原网页已经找不回来了,没法放在参考链接里了。

tab = "    "

dateOutput = true

function print_r(t)
    print_table(t, 0)
end

function print_table(t, i)
    local indent ="" -- i缩进,当前调用缩进
    for j = 0, i do
        indent = indent .. tab
    end
    for k, v in pairs(t) do
        if (type(v) == "table") then -- type(v) 当前类型时否table 如果是,则需要递归,
                local key = ""
                if type(k) ~= "number" then
                    key = k
                    end
            print(indent ..key, "{")
            print_table(v, i + 1) -- 递归调用
            print(indent .. "}")
        else -- 否则直接输出当前值
            if (dateOutput and type(v) == "number" and v > 100000) then
                v = os.date("%x", v)
            end
            if type(v)=="boolean" then
                v=(v and "true") or "false"
            end
            print(indent  .. k .. "=" .. v..",")
        end
    end
end

Lua测试文件

  1. 简单测试,在lua端成功print出东西
function test()
    print("成功啦!")
end
  1. 向lua传值
function simpleParam(value)
    print(value)
end
  1. 从lua拿值
function simpleParam()
    return 5,9
end
  1. 向lua传NSArray或者NSDictionarys
function complexParam(value)
    print_r(value)
end
  1. 从lua拿值
function complexParam()
    local s1 = {name = "a", age = 20}
    local s2 = {name = "b", age = 19}
    return {s1, s2}
end

OC生成Lua的state

state = luaL_newstate();
luaL_openlibs(state);
lua_settop(state, 0);

NSString *luaFilePath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"lua"];
NSString *luaContent = [NSString stringWithContentsOfFile:luaFilePath
                                                 encoding:NSUTF8StringEncoding
                                                    error:nil];

int err;
if (luaContent == nil || [luaContent isEqualToString: @""]) {
    NSLog(@"Lua_State initial fail,lua file is nil");
}else {
    err = luaL_loadstring(state, [luaContent cStringUsingEncoding: NSUTF8StringEncoding]);
    if (0 != err) {
        luaL_error(state, "cannot compile the lua file: %s",
                   lua_tostring(state, -1));
        return;
    }
    
    err = lua_pcall(state, 0, 0, 0);
    if (0 != err) {
        luaL_error(state, "cannot run the lua file: %s",
                   lua_tostring(state, -1));
        return;
    }
    
    NSLog(@"Lua_state initial success");
}

OC调用

  1. 简单测试,在lua端成功print出东西
lua_State* state = [[LuaBinding shareBinding] state];
lua_getglobal(state,"test");
lua_pcall(state, 0, 0, 0);
  1. 向lua传值
lua_State* state = [[LuaBinding shareBinding] state];
lua_getglobal(state,"simpleParam");
lua_pushnumber(state, 7);
lua_pcall(state, 1, 0, 0);
  1. 从lua拿值
lua_State* state = [[LuaBinding shareBinding] state];
lua_getglobal(state,"simpleParam");
lua_pcall(state, 0, 2, 0);
NSInteger result1 = (NSInteger)lua_tointeger(state, -1);
lua_pop(state, 1);
NSInteger result2 = (NSInteger)lua_tointeger(state, -1);
lua_pop(state, 1);
NSLog(@"%ld,%ld", (long)result1,(long)result2);
  1. 向lua传NSArray或者NSDictionarys
    这里可没有可以直接用的lua_pushXXXX的东西来用了,我现在的处理方式是自己判断类型,做后pushNumber、pushString等等。听说jar包那边的是用lua的userdata之类的东西,我并没有研究了,因为当时开发需求赶,并且我对lua并没有太多兴趣...
    虽然我没有userdata,但是最近一次测试,我们传了1外3M的数据文件进去处理,我们只用了0.1s,而安卓的第三方库用了10s...
    我唯一担心的是,内存这块的东西,因为确实对C和lua并不熟悉

代码参考

- (void)pushObject:(id)object state:(lua_State *)state{
    unsigned int outCount = (unsigned int)[object count];
    
    if ([object isKindOfClass:[NSDictionary class]]) {
        lua_createtable(state, outCount, 0);
        for (NSString* key in object) {
            id value = object[key];
            
            lua_pushstring(state, [key cStringUsingEncoding: NSUTF8StringEncoding]);
            if ([value isKindOfClass: [NSString class]]) {
                lua_pushstring(state, [value cStringUsingEncoding: NSUTF8StringEncoding]);
            } else if([value isKindOfClass: [NSNumber class]]) {
                lua_pushnumber(state, [value doubleValue]);
            } else {
                [self pushObject:value state:state];
            }
            
            lua_rawset(state, -3);
        }
    } else {
        lua_createtable(state, outCount, 0);
        for (int i = 0; i < outCount; i++) {
            lua_pushinteger(state, i + 1);
            
            id element = object[i];
            if ([element isKindOfClass: [NSString class]]) {
                lua_pushstring(state, [element cStringUsingEncoding: NSUTF8StringEncoding]);
            } else if([element isKindOfClass: [NSNumber class]]) {
                lua_pushnumber(state, [element doubleValue]);
            } else {
                [self pushObject:element state:state];
            }
            
            lua_settable(state, -3);
        }
    }
}
  1. 从lua拿NSArray或者NSDictionarys
    与第4条一样,没有现成的lua_toXXXX可用。

参考代码

- (id)readLuaTable:(lua_State *)state{
    int index = lua_gettop(state);
    lua_pushnil(state);
    
    id info = nil;
    while(lua_next(state, index) != 0)
    {
        if (info == nil) {
            if (lua_type(state, -2) == LUA_TNUMBER) {
                info = [NSMutableArray array];
            }else {
                info = [NSMutableDictionary dictionary];
            }
        }
        
        if(lua_isnumber(state, -1)){
            double value = lua_tonumber(state, -1);
            if ([info isKindOfClass: [NSMutableDictionary class]]) {
                [info setObject: @(value)
                         forKey: [NSString stringWithUTF8String: lua_tostring(state, -2)]];
            }else if ([info isKindOfClass: [NSMutableArray class]]) {
                [info addObject: @(value)];
            }
        }
        else if(lua_isstring(state, -1)){
            const char* value = lua_tostring(state, -1);
            if ([info isKindOfClass: [NSMutableDictionary class]]) {
                [info setObject: [NSString stringWithUTF8String: value]
                         forKey: [NSString stringWithUTF8String: lua_tostring(state, -2)]];
            }else if ([info isKindOfClass: [NSMutableArray class]]) {
                [info addObject: [NSString stringWithUTF8String: value]];
            }
        }
        else if(lua_isboolean(state, -1)){
            BOOL value = lua_toboolean(state, -1);
            if ([info isKindOfClass: [NSMutableDictionary class]]) {
                [info setObject: @(value)
                         forKey: [NSString stringWithUTF8String: lua_tostring(state, -2)]];
            }else if ([info isKindOfClass: [NSMutableArray class]]) {
                [info addObject: @(value)];
            }
        }
        else if(lua_istable(state, -1)){
            id value = [self readLuaTable: state];
            if (value != nil && [info isKindOfClass: [NSMutableDictionary class]]) {
                [info setObject: value
                         forKey: [NSString stringWithUTF8String: lua_tostring(state, -2)]];
            }else if (value != nil && [info isKindOfClass: [NSMutableArray class]]) {
                [info addObject: value];
            }
        }else {
            NSLog(@"未识别lua的类型");
        }
        
        lua_pop(state, 1);
    }
    return info;
}

参考

http://blog.stokedsoftware.com/blog/2012/02/04/scripting-ios-games-with-lua/

你可能感兴趣的:(OC与Lua调用交互(不使用第三方库))