ffi idea: strip null pointers

  • From: Cosmin Apreutesei <cosmin.apreutesei@xxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Mon, 4 Jun 2012 02:50:51 +0300

Hi,

Since everything in ffi that can take a NULL can also take a nil, I
propose getting rid of NULL pointers by transforming them to nil on
all pointer accessors (function return value, struct field access,
array element access, cast, initializer).

Pros:
- solving one of the two showstoppers on compatibility with luaffi
(not that this is the only way to solve it).
- bringing back the idioms `if not handle then` and `pinfo = pinfo or
default` etc.
- no more a difference between type(handle) == 'nil' and handle == nil
which was a useful Lua invariant.

Cons:
- speed loss ?
- any place where nil cannot be used in place of a NULL pointer ?

For me this would mean less bugs - since I made adjustments to the
code to get rid of NULLs as soon as possible it made my life easier.
Specifically, I made a function ptr(p) return p ~= NULL and p or nil
end which I apply over all functions that return a pointer so that
NULLs don't leak into the system and create subtle bugs because I
forgot to adjust some idioms to account for NULLs. For instance I use
`t[k] = handler` in an iteration as an idiom to collect only non-nil
values but NULLs would be collected too. Another idiom is `arg = arg
or default` where a NULL would prevent setting a default.

Other related posts: