Module lege.struct
Allows the creation of strict structs.
Strict structs defined by this module have strict field access (I.E. trying to get or set the value of a field that is undefined for a given struct type is an error).
Usage:
local struct = require "lege.struct"
-- Define a Point struct, to hold x and y coordinates
local Point = struct 'Point' {
x = 0,
y = 0,
}
-- Create a Point
local p = Point {
x = 10,
y = 20,
}
print(p) --> struct Point: 0xdeadbeaf
assert(p.x == 10)
assert(p.y == 20)
-- Trying to access or modify an undefined field is an error
-- print(p.z) --> Error: no field 'z' on struct Point
-- When constructing a new struct, unspecified fields get their default
values p = Point {x=1} assert(p.x == 1) assert(p.y == 0)
-- Struct fields can be modified as you'd expect, but don't set them to nil!
p.y = 42
assert(p.y == 42)
Meta Methods
| __tostring | Convert a struct type to a human-readable string. |
Functions
| returns... () | |
| _struct_err_nf (self, key) | Raises an error caused by access to an undefined struct field. |
| new_instance (instance) | Create a new struct type. |
| struct_body (fields) | Define a struct's body. |
| struct (string) | Create a struct type. |
Meta Methods
- __tostring
-
Convert a struct type to a human-readable string.
Currently we merely output the struct's name and address.
param:
- self struct The struct to convert to a string
Functions
- returns... ()
-
Returns:
-
A function struct that Allows you to define structs
- _struct_err_nf (self, key)
-
Raises an error caused by access to an undefined struct field.
Parameters:
Raises:
An error indicating which field was undefined, and on which struct type - new_instance (instance)
-
Create a new struct type.
This is used as a closure returned from struct_body, and creates a new
instance of a struct. Any unset fields are set to their default value as
defined by the struct type.
Parameters:
- instance table Table to use as the struct instance, including any pre-initialized fields
Returns:
-
table
The passed instance, modified to be a struct of the correct
type
Raises:
If instance contains undefined fields for the struct type - struct_body (fields)
-
Define a struct's body.
A closure over a struct's name returned from struct which creates a new
metatable for the struct type, and allows you to define what fields and
default values the struct has.
Parameters:
- fields table Fields and default values for the new struct type
Returns:
-
A closure new_instance over the struct type's name and fields to
create a new instance of the defined struct type
- struct (string)
-
Create a struct type.
Parameters:
- string name The struct's type name (used when converting to string)
Returns:
-
A
closure over name struct_body to allow you to specify the
struct's fields and default values