# Recursive calls between Lua and Swift

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

# 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.h

`#include "lua.h"int factorialExternal(lua_State *luaState);`

# FactorialWrapper.m

`#import "FactorialWrapper.h"#import "LuaSwiftRecursiveSwiftLua-Swift.h" // << ADJUST MEFactorial * 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.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

`-- factorialfunction factorial(n)    if (n == 0) then        return 1    else        return n * factorialExternal(n - 1)    endend`

# Summary

## SwiftUI | Download JSON and Display Images in a LazyVGrid

Get the Medium app