Home > Backend Development > Golang > How to use golang lua

How to use golang lua

(*-*)浩
Release: 2019-12-13 13:30:05
Original
3651 people have browsed it

How to use golang lua

There is a Lua virtual machine written in golang on github, called gopher-lua.

The corresponding relationship between the data types in lua and the data types in golang has been explained in the document. It is worth noting that the type starts with L and the name of the type starts with LT. (Recommended learning: go)

To convert data in golang to data in lua, it must be converted to a type starting with L:

str := "hello"
num := 10
L.LString(str)
L.LNumber(float64(num))
Copy after login

Data in lua is converted to For data in golang, the project provides functions such as ToInt and CheckString for conversion, but the type must be known in advance. If you do not know, you must perform type judgment:

value := L.Get(1)
switch value.Type() {
case lua.LTString:
case lua.LTTable:
....
}
Copy after login

You can also use gopher here -luar to facilitate type conversion.

golang and lua call each other functions

The function in golang must be converted to func(L *lua.State) int this This form can be injected into lua. The int of the return parameter represents the number of return parameters.

func hello(L *lua.State) int {
     //将返回参数压入栈中
     L.Push(lua.LString("hello"))
     //返回参数为1个
     return 1
}
//注入lua中
L.SetGlobal("hello", L.NewFunction(hello))
Copy after login

To call the lua function in golang, you need to define this function in the lua script first, and then call CallByParam:

//先获取lua中定义的函数
fn := L.GetGlobal("hello")
if err := L.CallByParam(lua.P{
    Fn: fn,
    NRet: 1,
    Protect: true,
    }, lua.LNumber(10)); err != nil {
    panic(err)
}
//这里获取函数返回值
ret := L.Get(-1)
Copy after login

The above is the detailed content of How to use golang lua. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template