string type conversions
nelua strings are defined as @record{data: *[0]byte, size: usize}, which is identical to span(byte), where 'data' is identical to cstring (barring any complaints about signed cchar).
nelua also expects strings to be immutable and for 'data' to always be zero-terminated. Violating these expectations can result in panicking runtime checks, among other surprising behaviors.
Legend:
- copy - get a freshly allocated copy of the input
- alias - reuse the input, without allocation
- stream - get individual values from the input, without allocation
- st - the input string
from string
- string -> span(byte): alias with
(@span(byte))(st)or implicitly, e.g.local sp: span(byte) = st(NB. don't use ordered fields initialization withspan(byte)) - string -> string: copy with
string.copy(st) - string -> cstring: alias with
cstring(st)or implicitly, e.g.C.puts(st) - string -> cstring: write to existing buffer with
string.fillcstring(st, buf, buflen) - string -> uint8: stream bytes with
for i, c in ipairs((@span(byte))(st)) do ... end. You can provide a type, likefor i, c: cchar in st do ... end - string -> uint32: stream Unicode codepoints with
for i, c in utf8.codes(st) do ... end
from span
- span(byte) -> string: alias with
(@string){sp.data, sp.size}
from sequence(byte)
- sequence(byte) -> span(byte): alias with
(@span(byte))(st) - sequence(byte) -> string: alias via span,
(@string){sp.data, sp.size}, or(@string){(@span(byte))(st).data, #st} - sequence(byte) -> cstring: copy via string into string.copy() to get zero termination, or unsafe alias via span,
cstring((@span(byte))(line).data)
from cstring
- cstring -> string: alias with
string(st), or implicitly - cstring -> span(byte): alias via string with
(@span(byte))(string(s1)) - cstring -> uint8: stream via
span(byte), withfor i, c in ipairs((@span(byte))(string(s1))) do ... end
from pointer and length
- -> string: alias, without zero-termination, with
(@string){data=p, size=n} - -> string: copy and zero-terminate with
string.copy({data=p, size=n})