Skip to content

Commit

Permalink
fix error when setting wrong struct field type
Browse files Browse the repository at this point in the history
  • Loading branch information
Bingjia Chen authored and Tim Cooper committed Jun 5, 2023
1 parent 6b0665c commit 2aa5885
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
2 changes: 1 addition & 1 deletion luar.go
Expand Up @@ -441,7 +441,7 @@ func lValueToReflectInner(L *lua.LState, v lua.LValue, hint reflect.Type, visite

lValue, err := lValueToReflectInner(L, value, field.Type, visited, nil)
if err != nil {
return reflect.Value{}, nil
return reflect.Value{}, err
}
t.FieldByIndex(field.Index).Set(lValue)
}
Expand Down
50 changes: 50 additions & 0 deletions struct_test.go
Expand Up @@ -399,3 +399,53 @@ func Test_struct_unexport_anonymous_field(t *testing.T) {
t.Errorf("expected test_unexport_anonymous_child to be nil, got %v", field)
}
}

type test_struct_convert_mismatch_type struct {
Str string
Int int
Bool bool
Float32 float32
NestChild Test_nested_child1
}

func Test_struct_convert_mismatch_type(t *testing.T) {
{
// struct conversion in function argument
L := lua.NewState()
defer L.Close()
n := test_struct_convert_mismatch_type{}

fn := func(s *test_struct_convert_mismatch_type) {
n = *s
}
L.SetGlobal("fn", New(L, fn))
testError(t, L, `return fn({Str = 111})`, "bad argument")
testError(t, L, `return fn({Int = "foo"})`, "bad argument")
testError(t, L, `return fn({Float32 = "foo"})`, "bad argument")
testError(t, L, `return fn({Bool = "foo"})`, "bad argument")
testError(t, L, `return fn({NestChild = {Name = 1}})`, "bad argument")

if n.Float32 != 0 || n.Int != 0 ||
n.Bool != false || n.Str != "" || n.NestChild.Name != "" {
t.Errorf("field(s) are set when the type is mismatched: %+v", n)
}

}

{
// field assignment
L := lua.NewState()
defer L.Close()
n := &test_struct_convert_mismatch_type{}
L.SetGlobal("c", New(L, n))
testError(t, L, `c.Str = 1`, "bad argument")
testError(t, L, `c.Int = "foo"`, "bad argument")
testError(t, L, `c.Bool = "foo"`, "bad argument")
testError(t, L, `c.NestChild.Name = 1`, "bad argument")

if n.Float32 != 0 || n.Int != 0 ||
n.Bool != false || n.Str != "" || n.NestChild.Name != "" {
t.Errorf("field(s) are set when the type is mismatched: %+v", n)
}
}
}

0 comments on commit 2aa5885

Please sign in to comment.