Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help me understand this piece of Lua code

Tags:

lua

I started programming in Lua few days ago. I have become familiar with the syntax and I have managed to write a module for Prosody XMPP server. I ran in to a snippet of code in Prosody server configuration(which is in Lua).

VirtualHost "example.com"
  enabled = false;
  ssl = {
    key = "certs/example.com.key";
    certificate = "certs/example.com.crt";
  };

I am trying to figure out how the table in the 2nd line is linked to the first line.

Is it a parameter to the VirtualHost function? i.e. can the code be written as:

VirtualHost "example.com", {
  enabled = false;
  ssl = {
    key = "certs/example.com.key";
    certificate = "certs/example.com.crt";
  };
};

Is there some Lua concept I need to study further?

like image 914
Harish Shetty Avatar asked Jan 12 '11 19:01

Harish Shetty


1 Answers

There is no direct connection between the first line and the rest. The first line is equivalent to VirtualHost("example.com") - you don't need parentheses if a function call is passed only a single string parameter.

Looking at Prosody's source code, what is happening here is that the code that loads the configuration file uses a combination of setfenv and setmetatable to trap writes into global variables (ssl and enabled). When you write enabled = false, it doesn't actually set the global variable enabled, but instead it calls a function defined by the Prosody code which sets the property on the currently defined virtual host.

This is all implemented in the parsers.lua.load function in core/configmanager.lua.

You can read about setfenv here and about setmetatable here (specifically this code uses the __newindex metamethod).

like image 115
interjay Avatar answered Nov 15 '22 11:11

interjay