Warning
- While pointer arithmetic can be powerful, it can also be a source of bugs if not handled carefully.
- Keep attention to respect memory allocations and boundaries.
Pointer math operations
Pointer objects supports as in C using some math operators to do calculations.
The result of an operation maybe another Pointer or an number for pointer substraction.
Pointer addition
You can add (+) a Lua integer to a Pointer, which will move the pointer forward by that number of elements.
Pointer substraction
You can substract (-) a Lua integer from a Pointer, which will move the pointer backward by that number of elements.
Subtracting one pointer from another is supported too, which gives the number of elements between them.
Example
--! luart-extensions
import c
-- Creates a Pointer from a C string
local c_ptr = c.Pointer(c.string("Hello LuaRT"))
-- Casts the pointer to a C string and adds 6 elements(chars), printing the resulting Pointer
print(c_ptr:as("char*") + 6)