From 2aa5885def8a7168875e5d2e469e4116584707c0 Mon Sep 17 00:00:00 2001 From: Bingjia Chen Date: Fri, 2 Jun 2023 16:36:18 +0800 Subject: [PATCH] fix error when setting wrong struct field type --- luar.go | 2 +- struct_test.go | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/luar.go b/luar.go index d7c8a27..3026a01 100644 --- a/luar.go +++ b/luar.go @@ -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) } diff --git a/struct_test.go b/struct_test.go index 1e0cf5a..c9a1ebb 100644 --- a/struct_test.go +++ b/struct_test.go @@ -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) + } + } +}