Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Help] Getting a return value from lua #110

Open
Beanzilla opened this issue Jan 24, 2023 · 1 comment
Open

[Help] Getting a return value from lua #110

Beanzilla opened this issue Jan 24, 2023 · 1 comment

Comments

@Beanzilla
Copy link

I have a lua script like below:

return {
    answer = 42,
    ok = true
}

I'd like to retrieve the table that the script has returned, I've seen the other issue #101, and I don't quite understand how to obtain the return value.

Perhaps I need an example of how to access it.

Just a short example will do, as once I see it I am sure I'll be able to work my way to understanding how to do it for further cases.

@TimVosch
Copy link

After performing DoString (or DoFile) the result will be at top of the stack.
Since you return a table you can fetch the items using L.GetField

Example:

func TestReturnDoString(t *testing.T) {
	L := lua.NewState()
	L.DoString(`return { answer = 42 }`)
	assert.True(t, L.IsTable(-1)) // Should be true!
	L.GetField(-1, "answer")
	assert.Equal(t, 42, L.ToInteger(-1))
}

Note that LoadString (or LoadFile) does not actually execute the file, but rather returns a function that contains the file. In that case you need to L.Call the loaded chunk first.

func TestReturnTableFromLoadString(t *testing.T) {
	L := lua.NewState()
	L.LoadString(`return { answer = 42 }`)
	assert.True(t, L.IsFunction(-1)) // Should be true!
	L.Call(0, 1)                     // Has 0 parameters, and returns 1 value
	// Returned value will now be at the top of the stack
	assert.True(t, L.IsTable(-1)) // Should be true!
	L.GetField(-1, "answer")
	assert.Equal(t, 42, L.ToInteger(-1))
}

To know what functions do with the stack, refer to the Lua Manual.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants