重归混沌 <
find...@gmail.com> 于2025年10月17日周五 11:43写道:
>
> > For this case, you can split the large string into a C string view struct first:
> >
> > struct string_slice {
> > const char *str;
> > size_t sz;
> > };
> >
> > struct string_slice string_view_array [];
> >
> > And store the string_slice * as a lightuserdata instead of a lua string .
> > When you use these strings, you can simply convert string_slice into
> > external string by
> >
> > struct string_splice *slice = (struct string_splice *)lua_touserdata(L, index);
> > lua_pushexternalstring(L, slice->str, slice->sz, NULL, NULL); //
> > NOTICE: it would be a null-terminated string.
>
> That approach would gradually make the lifetime management more complex.
If you want to simplify the lifetime, you can define a customized
version of external string,
Put the slice meta info after the external string data.
> If we could have a zero-cost string:sub, then many functions like
> string.unpack and string.find wouldn’t need extra init or pos
> parameters at all.
When you say "zero-cost", I guess you mean O(1) ? Creating an string
object can't be zero cost,
but lua_pushexternalstring() is already O(1) now.
You can implement it by lua_pushexternalstring .
For example, if you want to split a large string into many small ones,
all the sub strings can share the same memory (need a ref count in
the meta info of the C external string object),
--
http://blog.codingnow.com