Recursive calls between Lua and Swift

A common method of simplification is to divide a problem into subproblems of the same type. — Wikipedia: recursive

registerFunction

LuaWrapper.h

- (void) registerFunction: (lua_CFunction)function
withName: (const char *)name;

LuaWrapper.m

- (void) registerFunction: (lua_CFunction)function
withName: (const char *)name {
lua_register(luaState, name, function);
}

FactorialWrapper

FactorialWrapper.h

#include "lua.h"

int factorialExternal(lua_State *luaState);

FactorialWrapper.m

#import "FactorialWrapper.h"
#import "LuaSwiftRecursiveSwiftLua-Swift.h" // << ADJUST ME

Factorial * factorial;

int factorialExternal(lua_State *luaState) {
if (factorial == Nil) {
factorial = [[Factorial alloc] initWithScript: @""];
}

UInt64 n = lua_tointeger(luaState, -1L);
lua_pop(luaState, 1);

lua_Number res = [factorial
callFactorialWithState:luaState
value:n];
lua_pushnumber(luaState, res);

return 1;
}

Bridging.h

#import "FactorialWrapper.h"

Factorial Class

Factorial.swift

@objc(Factorial)
class Factorial : NSObject {

var lua : Lua
let ptrFname = strdup("factorial")

@objc
init(script: String) { // Objective-C: initWithScript
lua = Lua()
lua.setup()

let ptrScript = strdup(script)
lua.script(ptrScript)
free(ptrScript)

let funcName = strdup("factorialExternal")
lua.register(factorialExternal, withName: funcName)
free(funcName)
}

@objc
func callFactorial(state: OpaquePointer? = nil,
value: lua_Number) -> lua_Number {
// Objective-C: callFactorialWithState
return lua.call(state,
methode: ptrFname,
value: value)
}

deinit {
free(ptrFname)
lua.destruct()
}
}

ViewController.swift

let filename = Bundle.main.path(forResource: "script",
ofType: "lua")!

do {
let luaScript = try String(contentsOfFile: filename)

let fac = Factorial(script: luaScript)
let result = fac.callFactorial(value: lua_Number(100))
print(result)
} catch let error {
print("can not read file", filename, error)
}

script.lua

-- factorial
function factorial(n)
if (n == 0) then
return 1
else
return n * factorialExternal(n - 1)
end
end

Summary

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store