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

How to use golang lua

(*-*)浩
(*-*)浩 Original
2019-12-13 13:30:05 3548browse

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

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: .... }

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

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)

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!

Statement:
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
Previous article:Is golang leaf used a lot? Next article:Is golang leaf used a lot?