这是一个简单的 Objective-C <-> Lua 桥接器,模仿了 iOS 7 的 JavaScriptCore。
简单的使用可能如下所示
static NSString *const myScript =
LUA_STRING(
globalVar = { 0.0, 1.0 }
function myFunction(parameter)
return parameter >= globalVar[1] and parameter <= globalVar[2]
end
);
- (void)doLua {
LuaContext *ctx = [LuaContext new];
NSError *error = nil;
if( ! [ctx parse:myScript error:&error] ) {
NSLog(@"Error parsing lua script: %@", error);
return;
}
NSLog(@"globalVar is: %@", ctx[@"globalVar"]); // should print "globalVar is: [ 0.0, 1.0 ]"
id result = [ctx call:@"myFunction" args:@[ @0.5 ] error:&error];
if( error ) {
NSLog(@"Error calling myFunction: %@", error);
return;
}
NSLog(@"myFunction returned: %@", result); // should print "myFunction returned: '1'"
ctx[@"globalVar"] = @[ 0.2, 0.4 ];
result = [ctx call:@"myFunction" args:@[ @0.5 ] error:&error];
if( error ) {
NSLog(@"Error calling myFunction: %@", error);
return;
}
NSLog(@"myFunction returned: %@", result); // should print "myFunction returned: '0'"
}
更复杂的使用可能是
static NSString *const myScript =
LUA_STRING(
function moveView(view)
local center = view.center
center.y = center.y + 5
center.x = center.x + 5
view.center = center
end
);
@protcol UIViewLuaExports <LuaExport>
@property(nonatomic) CGFloat alpha;
@property(nonatomic) CGRect bounds;
@property(nonatomic) CGPoint center;
@property(nonatomic) CGRect frame;
// this can be called from Lua as view1.addSubview(view2)
- (void)addSubview:(UIView*)view;
// this can be called from Lua as view1.insertSubviewAboveSubview(view2, siblingSubview)
- (void)insertSubview:(UIView *)view aboveSubview:(UIView *)siblingSubview;
// this can be called from Lua as view1.insertSubviewBelowSubview(view2, siblingSubview)
- (void)insertSubview:(UIView *)view belowSubview:(UIView *)siblingSubview;
- (void)removeFromSuperview;
@end
@interface UIView (UIViewLuaExports) <UIViewLuaExports>
@end
@implementation UIView (UIViewLuaExports)
@end
- (void)doLua:(UIView*)onView {
LuaContext *ctx = [LuaContext new];
NSError *error = nil;
if( ! [ctx parse:myScript error:&error] ) {
NSLog(@"Error parsing lua script: %@", error);
return;
}
[ctx call:@"moveView" args:@[ onView ] error:&error];
if( error ) {
NSLog(@"Error calling myFunction: %@", error);
return;
}
}