GLOBAL L TYPE long*
GLOBAL x,y,result TYPE double

SETENVIRON "LANG","C"

INCLUDE "lua.bac"

L = luaL_newstate()
luaL_openlibs(L)

'push the function address to lua
lua_pushcfunction(L, ADDRESS(foo))

'give it a name in the lua script
lua_setglobal(L, "dofoo")

'open up a lua file in the current directory and run it
IF luaL_dofile(L, "sum.lua") THEN
    er$ = lua_tostring(L, -1)
    PRINT er$
END IF

lua_close(L)

FUNCTION foo(long* ls)

    LOCAL n,i TYPE int
    LOCAL sum TYPE double
        
    'number of arguments
    n = lua_gettop(ls)
    sum = 0
        
    'lua indices start with 1 - not 0
    FOR i = 1 TO n
        IF (lua_isnumber(ls, i)) EQ 0 THEN
            lua_pushstring(ls, "incorrect argument")
            lua_error(ls)
        END IF
        sum = sum + lua_tonumber(ls, i)
    NEXT i
        
    PRINT "From BaCon - Isn't Lua neat?"
        
    ' first result
    lua_pushnumber(ls, sum/n)
        
    ' second result
    lua_pushnumber(ls, sum)
                
    'number of results
    RETURN 2

END FUNCTION