Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-

Linked Lists in Lua

Name: Anonymous 2011-09-14 0:03

Alright, I'm trying to create a linked list in Lua, but I'm having a slight issue. I know how to do it, but not why it works.

Can someone explain the following line of code to me?

list = {next = list, value = v}

To create a linked list I would do something like the following.

for i = 1,5 do
    local v = io.read()
    list = {next = list, value = v}
end

Then to show it I would go.

do
   local l = list
   while l do
       print(l.value)
       l = list.next
   end
end

One again, all of it makes sense except the following.

list = {next = list, value = v}

If anyone here knows how this works and can explain it that would be great.

Name: Anonymous 2011-09-14 0:12

the second "list" is evaluated to the current value of "list", then "list" is rebound with = to the table containing the old value.

It's not so different from i = i + 1

Name: Anonymous 2011-09-14 0:18

>>2
Okay, so because the right side of the assignment is evaluated first the old table address is saved inside the table and a new object is created for the variable being assigned. If it's the first table then next is given a nil value.

Is that right? I think I get it now.

Name: Anonymous 2011-09-14 0:25

>>3
right.

it just looks a little zaney because it uses list before it is initialized (purposefully)

and it might be a bit confusing to a C programmer to have a heap object like a table just be thrown somewhere else and then overwritten, when it sort of looks like it's on the stack.

you should probably forget the heap/stack distinction. Lua doesn't even use it and has a register-based VM.

Name: Anonymous 2011-09-14 0:36

>>4
Thanks for the tips, but I'm not really a C programmer, at least not until I finish this book, all the exercises in it, and then apply the knowledge.

...and yet I still needed help for this.

Thanks!

Name: Anonymous 2011-09-14 1:27

This implementation of a linkedlist works but I don't like it.

Name: Anonymous 2011-09-14 2:07

Alright, I'm trying to create a linked list in Lisp, but I'm having a slight issue. I know how to do it, but not why it works.

(cons 'car '(cudder))

If anyone here knows how this works and can explain it that would be great.

Don't change these.
Name: Email:
Entire Thread Thread List