moonsharp icon indicating copy to clipboard operation
moonsharp copied to clipboard

unassigned local variable can sometimes hold values other than nil

Open ShadowTheAge opened this issue 5 years ago • 5 comments

lua code

for k,v in pairs{1} do local my; return my; end

Expected result: my == nil Actual result my is a table

(I am using MoonSharp for Unity)

ShadowTheAge avatar Dec 17 '19 00:12 ShadowTheAge

This is indeed an error, what seems to be happening is that as nothing is assigned to my, it receives the table {1}.

ghost avatar Feb 20 '20 15:02 ghost

I've investigated into same case and unassigned local variables accesses latest stack value and tries to interpret it as a tuple, assigning it's second value to local scope variable. I think AssignmentStatement should check whether rvalue array is not less than lvalue array and expand it with nil values pushed to stack if it is.

Aberro avatar May 02 '20 20:05 Aberro

I'll move my issue here.

This will output current value from the stack, while it should be nil value. `local x print(x)'

AssignmentStatement.Compile tells SymbolRefExpression to emit OpCode.StoreLcl with stackofs=0 and tupleidx=1 and this makes no sense in given context.

Aberro avatar May 02 '20 20:05 Aberro

Looks like I've finally figured it out, after several incorrect fixes: in AssignmentStatement.cs, replace m_RValues initialization:

40:			else
41:			{
----
42:				m_RValues = new List<Expression>();
+++
   				if(names.Count > 0)
					m_RValues = new List<Expression>(new Expression[] { new LiteralExpression(lcontext, DynValue.Nil) });
+++
43:			}

This should initialize uninitialized values with nil values.

Aberro avatar May 02 '20 23:05 Aberro

fix in pull request: https://github.com/moonsharp-devs/moonsharp/pull/280

Aberro avatar May 10 '20 18:05 Aberro