|
| 18 Oct 2016 08:31 PM |
Hi I would very much appreciate it if someone could help me print this table. This is what I have so far:
local tab={ [0] = "Here", [1] = "is", [2] = "some", [3] = "lua"} print(#tab) local i = 0 while i <= #tab do i = i + 1 print(tab[i]) end
The output is:
3 is some lua nil
I don't understand why it is printing 3 and printing nil. How could I fix this? |
|
|
| Report Abuse |
|
|
cntkillme
|
  |
| Joined: 07 Apr 2008 |
| Total Posts: 44956 |
|
|
| 18 Oct 2016 08:37 PM |
| The array part of Tables in Lua start from 1, and not only that but you have a logic problem in your loop: you're never printing tab[0] but instead printing tab[1], tab[2], tab[3], and tab[4] |
|
|
| Report Abuse |
|
|
Dev_Ryan
|
  |
| Joined: 10 Mar 2013 |
| Total Posts: 243 |
|
|
| 18 Oct 2016 08:38 PM |
use pairs. Example:
for k,v in pairs(tab) do print(k,v) end
|
|
|
| Report Abuse |
|
|
|
| 18 Oct 2016 09:04 PM |
@Dev_Ryan
Do you know how I would just print the values of the table? Basically just print the strings? |
|
|
| Report Abuse |
|
|
Burglered
|
  |
| Joined: 14 Jul 2011 |
| Total Posts: 962 |
|
|
| 18 Oct 2016 09:11 PM |
local tab={"Here", "is", "some", "lua"}
local i = 0 while i <= #tab - 1 do i = i + 1 print(tab[i]) end
|
|
|
| Report Abuse |
|
|
Burglered
|
  |
| Joined: 14 Jul 2011 |
| Total Posts: 962 |
|
|
| 18 Oct 2016 09:12 PM |
Oops.
local tab={"Here", "is", "some", "lua"}
local i = 0 while i <= #tab do print(tab[i]) i = i + 1 end
|
|
|
| Report Abuse |
|
|
cntkillme
|
  |
| Joined: 07 Apr 2008 |
| Total Posts: 44956 |
|
|
| 18 Oct 2016 09:16 PM |
| print(table.concat(tab, "\n")) |
|
|
| Report Abuse |
|
|
|
| 18 Oct 2016 09:27 PM |
| You should only use while loops when you don't know how many repeats you want. |
|
|
| Report Abuse |
|
|
|
| 18 Oct 2016 09:36 PM |
| @PhoenixSigns that's exactly what I need for what I am trying to do later once I learn all the parts I need |
|
|
| Report Abuse |
|
|