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

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)
}

Install MSYS2

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

Source Code

 

Add new comment