Error when attempting to create a function to reverse a table

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? I want to create a custom function so i can easily reverse a table!

  2. What is the issue? The code errors when trying to reverse a table

  3. What solutions have you tried so far? i tried to debug the lua code and it’s still erroring

After that, you should include more details if you have any. Try to make your topic as descriptive as possible, so that it’s easier for people to help you!

   - Custom Functions
local function TableReverse(Table) -- takes parameter of the table returns a reversed table
  return {}
end

local ReturnedTable = TableReverse() -- Table to reverse
  
local TestTable = TableReverse[15,16,17,18,19,20] -- should return 20,19,18,17,16 and 15!

print(TestTable)

image

Hello I’m trying to create custom functions to do things lua does not have with built in functions but i’m receiving an error why is this happening thanks for your help :slight_smile:

1 Like

I’m unsure if you can provide multiple values at once in that way, but you may be able to.
Try replacing it with this:

local TestTable = TableReverse({15,16,17,18,19,20})

Also, for the function, try this:

local function TableReverse(Table) -- takes parameter of the table returns a reversed table
  local FlippedTable = {}
  for i = #Table, 1, -1 do 
    FlippedTable[#Table-i+1] = Table[i]
  end
  return FlippedTable
end

Thank you that worked can you please explain what is happening here so i have a better idea thanks :slight_smile:

Here is a commented version:

local function TableReverse(Table) -- takes parameter of the table returns a reversed table
  local FlippedTable = {} --Initiates a new, blank table
  for i = #Table, 1, -1 do --Set i to the number of items in the original table, then count down to 1
    FlippedTable[#Table-i+1] = Table[i] --Every time it goes down, set the 1st (then 2nd, 3rd ect) value 
--   of the flipped table to the last (then 2nd last, 3rd last) value of the original table
  end
  return FlippedTable --Return the flipped table
end