Skip to content

Commit

Permalink
feat: 加入新函数load用于动态载入变量
Browse files Browse the repository at this point in the history
  • Loading branch information
fy0 committed Jun 18, 2024
1 parent 5daed6d commit 3513468
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
35 changes: 35 additions & 0 deletions builtin_functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,30 @@ func funcStr(ctx *Context, this *VMValue, params []*VMValue) *VMValue {
return NewStrVal(params[0].ToString())
}

func funcRepr(ctx *Context, this *VMValue, params []*VMValue) *VMValue {
return NewStrVal(params[0].ToRepr())
}

func funcLoad(ctx *Context, this *VMValue, params []*VMValue) *VMValue {
v := params[0]
if v.TypeId != VMTypeString {
ctx.Error = errors.New("(load)类型错误: 参数类型必须为str")
return nil
}

name := v.Value.(string)
val := ctx.LoadName(name, false, true)
if ctx.Error != nil {
return nil
}

if ctx.Config.HookFuncValueLoadOverwrite != nil {
val = ctx.Config.HookFuncValueLoadOverwrite(name, val, nil)
}

return val.Clone()
}

func funcDir(ctx *Context, this *VMValue, params []*VMValue) *VMValue {
typeId := params[0].TypeId
var arr []*VMValue
Expand Down Expand Up @@ -156,11 +180,22 @@ var builtinValues = map[string]*VMValue{
"int": nnf(&ndf{"int", []string{"value"}, nil, nil, funcInt}),
"float": nnf(&ndf{"float", []string{"value"}, nil, nil, funcFloat}),
"str": nnf(&ndf{"str", []string{"value"}, nil, nil, funcStr}),
"repr": nnf(&ndf{"repr", []string{"value"}, nil, nil, funcRepr}),
"abs": nnf(&ndf{"abs", []string{"value"}, nil, nil, funcAbs}),
"bool": nnf(&ndf{"bool", []string{"value"}, nil, nil, funcBool}),
"load": nnf(&ndf{"load", []string{"value"}, nil, nil, nil}),
// TODO: roll()

// 要不要进行权限隔绝?
"dir": nnf(&ndf{"dir", []string{"value"}, nil, nil, funcDir}),
// "help": nnf(&ndf{"help", []string{"value"}, nil, nil, funcHelp}),
}

func _init() bool {
// 因循环引用问题无法在上面声明
nfd, _ := builtinValues["load"].ReadNativeFunctionData()
nfd.NativeFunc = funcLoad
return false
}

var _ = _init()
14 changes: 14 additions & 0 deletions builtin_functions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,17 @@ func TestNativeFunctionConvert(t *testing.T) {
assert.True(t, valueEqual(funcStr(vm, nil, []*VMValue{na(ni(1), ni(2))}), ns("[1, 2]")))
assert.True(t, valueEqual(funcStr(vm, nil, []*VMValue{na(na(), ni(2))}), ns("[[], 2]")))
}

func TestNativeFunctionLoad(t *testing.T) {
vm := NewVM()
err := vm.Run("val = '123'; load('val')")
if assert.NoError(t, err) {
assert.True(t, valueEqual(vm.Ret, ns("123")))
}

vm = NewVM()
err = vm.Run("load('load')")
if assert.NoError(t, err) {
assert.True(t, valueEqual(vm.Ret, builtinValues["load"]))
}
}

0 comments on commit 3513468

Please sign in to comment.