Files
llgo/c/lua/_demo/table/table.go

61 lines
937 B
Go
Raw Normal View History

2024-06-30 19:35:45 +08:00
package main
import (
"github.com/goplus/llgo/c"
"github.com/goplus/llgo/c/lua"
)
func printTable(L *lua.State) {
2024-07-13 22:57:01 +08:00
L.Pushnil()
2024-06-30 19:35:45 +08:00
for L.Next(-2) != 0 {
2024-07-13 22:57:01 +08:00
key := L.Tostring(-2)
value := L.Tostring(-1)
2024-06-30 19:35:45 +08:00
c.Printf(c.Str("%s - %s\n"), key, value)
L.Pop(1)
}
L.Pop(1)
}
func main() {
2024-07-13 22:57:01 +08:00
L := lua.Newstate()
2024-06-30 19:35:45 +08:00
defer L.Close()
2024-07-13 22:57:01 +08:00
L.Openlibs()
2024-06-30 19:35:45 +08:00
2024-07-13 22:57:01 +08:00
L.Newtable()
2024-06-30 19:35:45 +08:00
2024-07-13 22:57:01 +08:00
L.Pushstring(c.Str("name"))
L.Pushstring(c.Str("John"))
L.Settable(-3)
2024-06-30 19:35:45 +08:00
2024-07-13 22:57:01 +08:00
L.Pushstring(c.Str("age"))
L.Pushnumber(30)
L.Settable(-3)
2024-06-30 19:35:45 +08:00
2024-07-13 22:57:01 +08:00
L.Pushstring(c.Str("John Doe"))
L.Setfield(-2, c.Str("fullname"))
2024-06-30 19:35:45 +08:00
2024-07-13 22:57:01 +08:00
L.Getfield(-1, c.Str("name"))
c.Printf(c.Str("%s\n"), L.Tostring(-1))
2024-06-30 19:35:45 +08:00
L.Pop(1)
2024-07-13 22:57:01 +08:00
L.Pushstring(c.Str("age"))
L.Gettable(-2)
age := int(L.Tonumber(-1))
2024-06-30 19:35:45 +08:00
c.Printf(c.Str("Age: %d\n"), age)
L.Pop(1)
c.Printf(c.Str("All entries in the table:\n"))
printTable(L)
}
2024-07-13 22:57:01 +08:00
/* Expected output:
John
Age: 30
All entries in the table:
age - 30.0
fullname - John Doe
name - John
*/