[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Nested Userdata
- From: Francisco Olarte <folarte@...>
- Date: Thu, 11 Nov 2021 15:48:20 +0100
On 10/11/2021 09.56, Patrick Kurth wrote:
> What is the best way to represent a structure such as my rectangle
> example in C? The definition in C is something like this:
>
> struct point
> {
> int x, y;
> };
>
> struct rectangle
> {
> point bl;
> point tr;
> };
If you can live with an extra pointer ( there are better ways, but
this is the easier to explain ) you can do something likethis:
struct point_ud { point * p, point pp };
struct rectangle_ud { rectangle * r, rectangle * r};
Code all your normal methods to use point_ud.p and rectangle_ud.r,
then for your constructors:
Normal point constructor, newpoint(x,y): allocate a point_ud with 0
userdatas, set p=&pp, fill and return it.
Same for normal rectangle constructor.
Now, method rectangle:bl(), two forms. If by value it is trivial, if
you want to be a ref make a method bl which gets the rectangle_ud ptr.
Allocate a point with 1 userdata. Stash the rectangle (lua) user data
in it. Make point.b point to rectangle.bl.
If you want a rectangle array, more or less the same. Code a
rect_array_ud { int n, rectangle[] a } ( or rectangle * ). When
indexed with a valid index make a rectangle_ud with 1 userdata, stash
array there, point rectanle.r to the appropiate element.
You can even code a dettach method ( I do it in some similar system I
use ), i.e. in point to detach you do "if (pud.p != & pud.pp) { pud.pp
= *(pud.p); pud.p=&pud.pp; pushnil, setuservalue }
It can be optimized a lot, i.e.you can allocate just the pointers when
being indirect, but this is simple todo if your structs are not that
large and you do not use too many of them ( in the lua side ).
Francisco Olarte.