lua/vm_test.go

77 lines
1.5 KiB
Go

// Package lua ...
//
// Description : lua ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2024-11-14 18:08
package lua
import (
"fmt"
"testing"
)
func TestNewVm(t *testing.T) {
scriptTable := map[string]string{
"json": `local json = require("json")
local lua_table = {
name = "wx771720",
age = 18,
married = true,
skills = {"typescript", "unity", "lua"}
}
local json_str = json.encode(lua_table)
print(json_str) -- 输出JSON字符串`,
"http": `
local http = require("http.request")
-- 创建一个HTTP请求的选项表
local options = {
url = "http://example.com",
method = "GET",
}
-- 发起请求
local res, code = http.request(options)
-- 检查请求是否成功
if code == 200 then
print("请求成功,下面是返回内容:")
print(res)
else
print("请求失败,状态码:" .. code)
end
`,
}
if err := InitVM(1024, nil, scriptTable); err != nil {
panic(err.Error())
}
_, err := VMInstance.RunPreCompileScript("json")
fmt.Println(err)
_, err = VMInstance.RunPreCompileScript("http")
fmt.Println(err)
}
func TestNewVM_Map_Param(t *testing.T) {
scriptTable := map[string]string{
"json": `
local json = require("json")
print(jsonData.name)
local json_str = json.encode(jsonData)
print(json_str) -- 输出JSON字符串`,
}
if err := InitVM(1024, nil, scriptTable); err != nil {
panic(err.Error())
}
_, err := VMInstance.RunPreCompileScript("json", ScriptParam{Name: "jsonData", Value: map[string]any{
"name": "白茶清欢",
}})
fmt.Println(err)
}