Accessing an Existing PostgreSQL Connection from Lua

“Accessing a PostgreSQL database from Lua is easy, just ‘require ‘pgsql’, then do a pgsql.connectdb() and start executing queries. But this assumes that your program is written entirely in Lua, which might not always be the case.

This article describes techniques to access an existing PostgreSQL connection from Lua, i.e. a connection that was created in a C program that embeds a Lua interpreter. This is the typical use case when Lua is being used as an embedded language for extensions (and which is what Lua was designed for in the first place).

It is assumed that a software written in the C language embeds a Lua interpreter. A connection to a PostgreSQL server is made in the C code and a Lua script accesses this connection using the luapgsql module found at https://github.com/mbalmer/luapgsql…&#8221;