Jump to content




Multiple return values into table


  • You cannot reply to this topic
4 replies to this topic

#1 Bob

  • New Members
  • 1 posts

Posted 29 December 2014 - 02:22 PM

Hi,

I've been programming my own to-do list system in ComputerCraft (TPPI, survival), and I've stumbled upon something which I suspect is a bug/omission in the Lua implementation:

When I have a function that returns multiple arguments (for instance, term.current().getCursorPos()), and I want to directly use the results by putting them into a table like so:

ct = term.current()
local cy = {ct.getCursorPos()}[1]

I get the following error:

bios:366: [string "board"]:(line nr. of the "local cy..." line): unexpected symbol



While the Lua documentation states that this code should work, on this page, quoting:

function foo0 () end				  -- returns no results
function foo1 () return 'a' end	   -- returns 1 result
function foo2 () return 'a','b' end   -- returns 2 results

Quote

A constructor also collects all results from a call, without any adjustments:

a = {foo0()}		 -- a = {}  (an empty table)
a = {foo1()}		 -- a = {'a'}
a = {foo2()}		 -- a = {'a', 'b'}



Am I doing something wrong, perhaps misreading the documentation? Or is this a bug?

#2 Dragon53535

  • Members
  • 973 posts
  • LocationIn the Matrix

Posted 29 December 2014 - 03:12 PM

local cy = {ct.getCursorPos()}[1] --# This little [1] is invalid.
Can't do this...
local cy = {ct.getCursorPos()}
Works, however if you're wanting to only have the first index as a table to hold the data you need to do this:
local cy = {}
cy[1] = {ct.getCursorPos()}

Edited by Dragon53535, 29 December 2014 - 03:12 PM.


#3 Lyqyd

    Lua Liquidator

  • Moderators
  • 8,465 posts

Posted 29 December 2014 - 03:29 PM

The first index won't get you a "y" value of any sort anyway. If I recall correctly, this may work:

local cy = ({ct.getCursorPos()})[2]


#4 Lignum

  • Members
  • 558 posts

Posted 29 December 2014 - 03:29 PM

View PostDragon53535, on 29 December 2014 - 03:12 PM, said:

local cy = {ct.getCursorPos()}[1] --# This little [1] is invalid.
Can't do this...
local cy = {ct.getCursorPos()}
Works, however if you're wanting to only have the first index as a table to hold the data you need to do this:
local cy = {}
cy[1] = {ct.getCursorPos()}

You can also do this:
local cy = ({ ct.getCursorPos() })[1]

EDIT: Ninja'd

Edited by Lignum, 29 December 2014 - 03:29 PM.


#5 MKlegoman357

  • Members
  • 1,170 posts
  • LocationKaunas, Lithuania

Posted 29 December 2014 - 04:46 PM

To explain why that didn't work: Lua just doesn't let you index a table directly after it's constructor ( { ... } ) so you have to enclose it in parenthesis if you want to do that:

local t = {1, 2, 3}[2] --// wrong way

local t = ({1, 2, 3})[2] --// right way






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users