lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

En réponse à Nick Trout <>:

> >>Basically, Lua-swig generates 'userdata' for constants in order to
> avoid them to
> be overwritten as if they were simple Lua global variables.
> On the other hand, this trick also apply to global variables and
> permits
> to uses
> 'C' global variables (as long as they are of some basic type, char,
> int,
> float...) as Lua global variables: writing to them modify the actual C
> variable
> (as intented).
> Hope it makes this "inefficient" choice a little bit clearer.
> I'm not an expert on tag methods. From what I remember you can only
> settagmethods on tables and userdata. Hence your decision? I just
> wondered if there was a solution which didnt require the allocs (ie.
> alloc memory and create a userdata object for every readonly
> constant).
> Our code is particularly sensitive to this as we want to avoid
> fragmentation.
> eg.
> readonlytag = newtag()
> settagmethod(readonlytag,'getglobal',
>         function (obj,t)
>           return t.value
>         end )
> settagmethod(readonlytag,'setglobal',
>         function (x)
>           error("Cant do that")
>         end )
> -- this bit could be generated by the binding
> my_pi = { value=3.1415927 }
> settag(my_pi,readonlytag)
> print (my_pi)  -- will print value
> my_pi = 1  -- throws an error
> You could then have another tag method for readwrite which wrote
> through
> back to the C code instead of giving an error.
> Regards,
> Nick

Your description makes clear what the C code does, except -as you mentioned-
that it apply tags to userdata instead of table.
These usedata are small chunks of memory (a long) allocated at program start
instead of requesting a table from the Lua memory. In terms of memory footprint,
I am not sure that allocating as many tables as constants is deeply different
from allocating as many userdatas.
For writing back to the C variable, you also need to keep a pointer to the C
variable and you end up with allocating memory for the table (from Lua) and for
keeping the pointer: userdata saves you the table allocation here.

If I understand correctly, you are concerned with memory fragmentation, but -in
this case- those allocation are made early in the initialisation process and
never freed, it does consume memory, not fragment it. On the other hand, it also
consumes less memory than tables.

-- luagnome  <>