Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anything like pointers in Lua?

Tags:

pointers

lua

I'm new to Lua and I want to create a table [doh] which would store values like:

parent.child[1].value = "whaterver"
parent.child[2].value = "blah"

however, most often there's only one child, so it would be easier to access the value like this:

parent.child.value

To make things simpler, I would like to store my values, in a way, that

parent.child[1].value == parent.child.value

But to do this I would have to store this value twice in the memory. Is there any way I could do it, so that:

parent.child.value points to parent.child[1].value

without storing the value twice in the memory?

Additional question is, how to check how much memory does a table take?

like image 374
Krystian Avatar asked Dec 08 '11 12:12

Krystian


People also ask

Can you do ++ in Lua?

++ is not a C function, it is an operator. So Lua being able to use C functions is not applicable. Possible duplicate of stackoverflow.com/questions/7855525/….

Are there lists in Lua?

The Linked lists in Lua are of two kinds, namely singly-linked lists and doubly linked list. A singly linked list in Lua will have a reference pointing to the first node in a singly linked list, and there is a reference from each node to the next node in a singly linked list.

Are there arrays in Lua?

In Lua, arrays are implemented using indexing tables with integers. The size of an array is not fixed and it can grow based on our requirements, subject to memory constraints.

What is %f Lua?

In Lua, the following are the available string formatting syntax or string literals for different datatypes: %s : This serves as a placeholder for string values in a formatted string. %d : This will stand in for integer numbers. %f : This is the string literal for float values.


1 Answers

but the value will be stored as string, so it's a string that needs to be referenced in both places, not table.

First, all types (except booleans, numbers and light userdata) are references - if t is a table and you do t2 = t, then both t and t2 are references to the same table in memory.

Second thing - string are interned in Lua. That means that all equal strings, like "abc" and the result of "ab".."c" are actually a single string. Lua also stores only references to strings. So you should not worry about memory - there is only a single instance of the string at a time.

You can safely do parent.child.value = parent.child[1].value, you will only use a memory for one slot in a table (a few bytes), no string will be copied, only referenced.

like image 183
Michal Kottman Avatar answered Oct 03 '22 08:10

Michal Kottman