美文网首页
Lua实践1

Lua实践1

作者: YM_1 | 来源:发表于2016-01-04 15:29 被阅读156次

    听到有朋友说lua可以进行线上版本bug的修复,就试着学习一下,用到的框架地址:https://github.com/alibaba/wax ,很多网上的资料说不支持64位,但现在看来是已经支持了。

    Use with cocoa pods

    add
    
     pod 'wax', :git=>'https://github.com/alibaba/wax.git', :tag=>'1.1.0'
    
    then you can run lua code.放置AppDelegate中。
    
    wax_start(nil, nil);
    wax_runLuaString("print('hello wax')");
    

    记的导入wax.h
    运行成功,说明你已经成功集成。

    在本地创建一个空的文件,文件命名为test.lua。

    waxClass{"VC1",UIViewController}
    function touchesBegan_withEvent(self,touches,event)
    self:view():setBackgroundColor(UIColor:blueColor())
    end
    

    创建ViewController命名为VC1,实现方法

    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
        NSLog(@"sss");
    }
    
    

    在AppDelegate中

     - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        
        wax_start("test.lua", nil);
        
        return YES;
    }
    

    运行下你会发现VC1 中的touchesBegan方法被替换了。VC1的背景颜色变成蓝色了。
    以上就是本地运行lua文件的效果。当然更多的时候我们是从服务器上把lua文件下载本地,然后运行时进行一些有问题的解决(替换方法等)。这里只做简单的思路介绍。

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        
        [self downloadLuaFile];
         return YES;
    }
    
    
    - (void)downloadLuaFile{
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *fileName = @"change_002.lua";     //本地要保存的文件名称。
            NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSString *directory = [doc stringByAppendingPathComponent:fileName];
            
            NSURL *url=[NSURL URLWithString:@"http://localhost/xxxx.lua"];        //lua文件的服务器地址
    
            NSURLRequest *request=[NSURLRequest requestWithURL:url];
            
            NSError *error=nil;
            
            NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
            
            if([data length]>0)
                
            {
                NSLog(@"下载成功");
                if([data writeToFile:directory atomically:YES]){
                    NSLog(@"保存成功");
                    NSString *luaFilePath = [[NSString alloc ] initWithFormat:@"%@/?.lua;%@/?/init.lua;%@/?.dat;",doc, doc,doc];
                    setenv(LUA_PATH, [luaFilePath UTF8String], 1); //设置LUA路径
                    wax_start("change_002.lua", nil);
                }else {
                    NSLog(@"保存失败");
                }
            } else {
                NSLog(@"下载失败,失败原因:%@",error);
            }
        });
    }
    
    

    基本用法就是这样,剩下的一些逻辑可以自己完善。
    比如通过请求接口获取lua文件的地址。对已经存在的lua文件在应用启动的时候应该做什么样的操作。后面有时间会去更深入的学习lua的实用技巧

    相关文章

      网友评论

          本文标题:Lua实践1

          本文链接:https://www.haomeiwen.com/subject/oehahttx.html