You're right in that *every* userdata in Lua has an environment table. If you want to compare it with LUA_ENVIRONINDEX you should make sure all your C functions share this same environment.
I solved this in my Lua/APR binding by initializing all userdata with a default environment (shared between all userdata created by Lua/APR). When I want a userdata to have a unique environment I check whether the current environment is the same table as the shared environment, if it is then I create a new table and set that as the environment:
Why wouldn't all my C functions share the same environment ? What operations change this environment ?
https://github.com/xolox/lua-apr/commit/14efa65b3ae37c2f10ba192db08e52fffe14363b
This might not be the most efficient approach but it seemed the least error prone solution to me.
- Peter Odding