Call Lua from Kotlin or embed Lua inside Kotlin

Submitted by Dickens A S on Sat, 11/23/2019 - 06:20

Embedded Lua inside Kotlin

GitHub: https://github.com/dickensas/kotlin-gradle-templates/tree/master/embed-lua

Compile and Execute from MSYS2 or Cygwin with python development C header files  

Demo output

Lua in Kotlin

Lua code which is running inside Kotlin

function f1()
    io.write("f1 Lua function called from kotlin.\n")
end

function square(n)
    io.write("square Lua called from Kotlin, with parameter=")
    io.write(tostring(n))
    n = n * n
    return(n)
end

The Kotlin code which runs the lua

package plot

import lua.*
import kotlinx.cinterop.*

fun main() {
    var L = luaL_newstate()
    luaL_openlibs(L)
    
    //Load lua file from current directory
    luaL_loadfilex(L, "test.lua", null)
    lua_pcallk(L, 0, LUA_MULTRET, 0, 0, null)
    
    //trigger function "f1" defined in the lua file
    lua_getglobal(L, "f1")
    lua_pcallk(L, 0, LUA_MULTRET, 0, 0, null)
    
    //trigger function "square" defined in the lua file with parameters
    lua_getglobal(L, "square")
    lua_pushnumber(L, 6.toDouble())
    lua_pcallk(L, 1, LUA_MULTRET, 0, 0, null)
    
    //get the return value of previously invoked function
    var mynumber = lua_tonumberx(L, -1, null)
    println("Lua result value: ${mynumber}")
    
    lua_close(L)
}

MSYS2 : https://www.msys2.org/

This is required for windows to download pre-compiled libraries and its headers

pacman -S mingw-w64-x86_64-lua

change x86_64 to i686 for 32 bit widows

For Python use is code embed python in kolin

For Ruby use this code embed ruby in kotlin

For R use this code embed R in kotlin

For TCL use this code embed tcl in kotlin

 

Add new comment