winreg

Jas Latrix

All Rights Deserved. Use at your own risk!. Shake well before using.

Table of Contents

1. Introduction
2. Root key prefix
3. Access Option
4. winreg
4.1. Function(s) of winreg
5. RegistryObject
5.1. Method(s) of RegistryObject

1. Introduction

winreg is a Lua binary module to Access Microsoft(R) Windows(R) Registry. The registry is a system-defined database that applications and Microsoft(R) Windows(R) system components use to store and retrieve configuration data.

Load the module via the require function (make sure Lua can find the module), for example:

require"winreg"

-- prints all the special folders
hkey = winreg.openkey[[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion]]

skey = hkey:openkey([[Explorer\Shell Folders]])
for name in skey:enumvalue() do
	print("\nname: " .. name
	   .. "\npath: " .. skey:getvalue(name))
end

2. Root key prefix

The function createkey and openkey needs a root key prefix. It must be one of this strings:

Table 1. Root Key Prefix

Root key NameAbbreviation
HKEY_CURRENT_USERHKCU
HKEY_LOCAL_MACHINEHKLM
HKEY_CLASSES_ROOTHKCR
HKEY_USERSHKU
HKEY_CURRENT_CONFIGHKCC

3. Access Option

The function createkey and openkey needs a security access for the new key. It must be a string containing one of this character.

Table 2. Key Access

CharDescription
'w'Permission to create subkeys and set subkey data
'r'Permission to query subkey data and enumerate subkeys
'a'All access

If no argument is given the default is 'a'

4. winreg

winreg the global table of the registry module.

Use createkey to create a registry key or use openkey to open an existing registry key. Those two function will return a registry object

4.1. Function(s) of winreg

4.1.1. createkey

Creates the specified registry key. If the key already exists in the registry, the function opens it.
Syntax
winreg.createkey(str_subkey, str_access)
Arguments
str_subkey
Name of subkey to create. It must be prefix with a rootkey, see Section 2, “Root key prefix”
str_access
Security access option, see Section 3, “Access Option”.
Returns
Successthe created registry object
Failurenil.

4.1.2. openkey

Opens the specified registry key
Syntax
winreg.openkey(str_subkey, str_access)
Arguments
str_subkey
Name of subkey to open. It must be prefix with a rootkey, see Section 2, “Root key prefix”
str_access
Security access option, see Section 3, “Access Option”.
Returns
Successa registry object
Failurenil.
Remarks
You can use this function to establishes a connection to a predefined registry handle on another computer by setting the format of str_subkey to:
\\COMPNAME\ROOTKEY
COMPNAME is the name of the remote computer. ROOTKEY must be HKEY_LOCAL_MACHINE or HKEY_USERS.

5. RegistryObject

This object holds a registry handle (HKEY). The handle is automatically closed when the object is destroyed.

5.1. Method(s) of RegistryObject

5.1.1. close

Releases the registry object's key handle
Syntax
RegistryObject:close()
Returns
SuccessReference to RegistryObject it self
Failurenil.
Example
require"winreg"			
reg = winreg.openkey("HKEY_LOCAL_MACHINE\\SOFTWARE")
reg:close() -- reg is now useless but not nil
-- this is failure
reg:openkey(".lua"):setvalue("","lua_script","sz")

5.1.2. createkey

Creates the specified registry key in RegistryObject. If the key already exists in the registry, the function opens it.
Syntax
RegistryObject:createkey(str_subkey)
Arguments
str_subkey
name of subkey to create
Returns
Successa new registry object
Failurenil.
Example
require"winreg"
hkey = winreg.openkey([[HKCU\SOFTWARE]])
 pkey = hkey:createkey("PARENTKEY")
  ckey = pkey:createkey("CHILDKEY")

val  = "TESTVALUE"
dat  = "TESTDATA"
ckey:setvalue(val, dat)

tkey = winreg.openkey([[HKCU\SOFTWARE\PARENTKEY\CHILDKEY]])
assert(tkey:getvalue(val) == dat)

5.1.3. deletekey

Deletes a key and all its descendents.
Syntax
RegistryObject:deletekey(str_subkey)
Arguments
str_subkey
The name of subkey to delete
Returns
SuccessReference to RegistryObject it self
Failurenil.
Example
require"winreg"
hkey = winreg.createkey([[HKCU\Software\PARENTKEY\CHILDKEY]])
hkey:setvalue("VALUE1", "STRING")
hkey:setvalue("VALUE2", 2^32)
hkey:setvalue("VALUE3", {"awecq", "wecqw", "qweqwe"})
hkey:close()

hkey = winreg.createkey([[HKCU\Software\PARENTKEY\CHILDKEY\CHILDKEY2]])
hkey:setvalue("VALUE4", "%windir%", "expand_sz")
hkey:setvalue("VALUE5", 45)
hkey:close()

xkey = winreg.openkey([[HKCU\Software]])
assert(xkey:deletekey("PARENTKEY"))

5.1.4. deletevalue

Removes a named value from the RegistryObject.
Syntax
RegistryObject:deletevalue(str_value)
Arguments
str_value
The name of value to delete
Returns
SuccessReference to RegistryObject it self
Failurenil.
Example
require"winreg"
hkey = winreg.createkey([[HKCU\Software\PARENTKEY\CHILDKEY]])
hkey:setvalue("VALUE1", "STRING")
hkey:setvalue("VALUE2", 2^32)
hkey:setvalue("VALUE3", {"awecq", "wecqw", "qweqwe"})
hkey:close()

xkey = winreg.openkey([[HKCU\Software\PARENTKEY\CHILDKEY]])
assert(xkey:deletevalue("VALUE1"))
assert(xkey:deletevalue("VALUE2"))
assert(xkey:deletevalue("VALUE3"))

5.1.5. enumkey

Returns an enumerator function for for-in-loops. The function returns the name of a subkey each time it is called.
Syntax
RegistryObject:enumkey()
Returns
SuccessEnumerator function for for-in-loops
Failurenil.
Remarks
While enumerating, DO NOT make calls to any functions that might change the key being enumerated.
Example
require"winreg"
-- Enumerate Application paths
rkey = [[HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths]]
hkey = winreg.openkey(rkey)
for k in hkey:enumkey() do
	print(k,(hkey:openkey(k):getvalue()))
	collectgarbage()
end

5.1.6. enumvalue

Returns an enumerator function for for-in-loops. The function returns two values each time it is called, the value name and value type (see Table 4, “Data Type”).
Syntax
RegistryObject:enumvalue()
Returns
SuccessEnumerator function for for-in-loops
Failurenil.
Remarks
While enumerating, DO NOT make calls to any registration functions that might change the key being enumerated.
Example
require"winreg"
-- Enumerate start up programs

rkey = "HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"
hkey = winreg.openkey(rkey)

print('\n'..rkey..":")
for name, kind in hkey:enumvalue() do
	print("\nname: " .. name
	.. "\ncommand: " .. hkey:getvalue(name))
end

rkey = "HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce"
hkey = winreg.openkey(rkey)

print('\n'..rkey..":")
for name, kind in hkey:enumvalue() do
	print("\nname: " .. name
	.. "\ncommand: " .. hkey:getvalue(name))
end

5.1.7. flushkey

Writes all the attributes of the registry object's key handle into the registry.
Syntax
RegistryObject:flushkey()
Returns
SuccessReference to RegistryObject it self
Failurenil.
Remarks
An application should only call flushkey if it requires absolute certainty that registry changes are on disk. In general, flushkey rarely, if ever, need be used.

5.1.8. getinfo

Retrieves information about the registry object's key handle
Syntax
RegistryObject:getinfo()
Returns

If the function succeeds, the return value is a table having this value

KeyTypeDescription
classstringclass name
subkeysnumbernumber of subkeys
valuesnumbernumber of value entries
maxsubkeylennumberlongest subkey name length
maxclasslennumberlongest class string length
maxvaluelennumbervalue name length

If the function fails, the return value is nil

Example
require"winreg"
rkey = [[HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer]]
info = winreg.openkey(rkey):getinfo()
print("number of subkeys : '" .. info.subkeys .. "'")
print("longest subkey name length : '" .. info.maxsubkeylen .. "'")
print("longest class string length : '" .. info.maxclasslen .. "'")
print("number of value entries : '" .. info.values .. "'")
print("longest value name length : '" .. info.maxvaluelen .. "'")
print("class string : '" .. info.class .. "'")

5.1.9. getstrval

Retrieves the data for a specified value name associated with an open registry key. The return value is string.
Syntax
RegistryObject:getstrval(str_value)
Arguments
str_value
The name of value to query.
Returns

If the function succeeds, the return value is a string, see table below for how data string conversion is done.

Table 3. Data Type String Conversion

TypeDescriptionConversion
1A null-terminated string.Lua string null not included.
2A null-terminated string that contains unexpanded references to environment variables (for example, "%PATH%").Lua string null not included. References to environment variables are expanded
3binary dataLua string containing binary data
4A 32-bit numberThe number converted to string
7An array of null-terminated strings, terminated by two null characters.Th same string

If the function fails, the return value is nil

Example
require"winreg"
rkey = "HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"
hkey = winreg.openkey(rkey)
for name, kind in hkey:enumvalue() do
	print("\nname: " .. name
	.. "\nvalue: " .. hkey:getstrval(name))
end
	

5.1.10. getvaltype

Returns the value type.
Syntax
RegistryObject:getvaltype(str_value)
Arguments
str_value
The name of value to query.
Returns
If the value name does not exist, return nil. If the value name exist, return its type see Table 4, “Data Type”
Example
require"winreg"
rkey = "HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"
hkey = winreg.openkey(rkey)
for name, kind in hkey:enumvalue() do
	print("\nname: " .. name
	.. "\ntype: " .. hkey:getvaltype(name))
	assert(kind == hkey:getvaltype(name))
end
	

5.1.11. getvalue

Retrieves the data and type for a specified value name associated with an open registry key.
Syntax
RegistryObject:getvalue(str_name)
Arguments
str_name
The name of the value to be queried
Returns

If the function succeeds, the return value is the data and it's type. see table below

Table 4. Data Type

TypeDescription
1data is a string (REG_SZ)
2data is a string that contains unexpanded references to environment variables (for example, "%COMSPEC%") (REG_EXPAND_SZ).
3data is a string containing binary data (REG_BINARY)
4data is a number(A 32-bit number) (REG_DWORD)
7data is a table conataining strings (REG_MULTI_SZ)

If the function fails, the return value is nil

5.1.12. load

Creates a subkey under registry object's key handle and stores registration information from a specified file into that subkey
Syntax
RegistryObject:load(str_key, str_file)
Arguments
str_key
The name of the key to be created under registry object's key handle
str_file
The name of a file that has registration information. This file must have been created with the save function. Under the file allocation table (FAT) file system, the filename may not have an extension.
Returns
SuccessReference to RegistryObject it self
Failurenil.
Remarks

The MS Win32 API documentation implies registry object's key handle must be open using only HKEY_USER or HKEY_LOCAL_MACHINE or \\Computername\HKEY_USER or \\Computername\HKEY_LOCAL_MACHINE as the subkey

This registration information is in the form of a hive. A hive is a discrete body of keys, subkeys, and values that is rooted at the top of the registry hierarchy. A hive is backed by a single file and .LOG file.

Example
require"winreg"
hkey = winreg.openkey([[HKLM]])
hkey:load("PARENTKEY", "TESTREGFILE")

5.1.13. openkey

Opens the registry key under registry object's key handle
Syntax
RegistryObject:openkey(str_subkey)
Arguments
str_subkey
Name of subkey to open.
Returns
Successa new registry object
Failurenil.
Example
require"winreg"
-- Enumerate shell folders
hkey = winreg.openkey([[HKCU\Software\Microsoft\Windows\CurrentVersion]])
skey = hkey:openkey("Explorer\\Shell Folders")
for name, kind in skey:enumvalue(true) do
	print("\nname: " .. name .. " (type " .. kind .. ")")
end

5.1.14. replace

Replaces the file backing a key and all its subkeys with another file, so that when the system is next started, the key and subkeys will have the values stored in the new file
Syntax
RegistryObject:replace(str_subkey, str_newfile, str_oldfile)
Arguments
str_subkey
The name of a key whose subkeys and values are replaced by this function.
str_newfile
The name of a file that has registration information. This file must have been created with the save function. Under the file allocation table (FAT) file system, the filename may not have an extension.
str_oldfile
The name of a file that receives a backup copy of the registry information being replaced. If this file is created under the FAT file system, it should not have an extension
Returns
SuccessReference to RegistryObject it self
Failurenil.
Remarks

The MS Win32 API documentation implies registry object's key handle must be open using only HKEY_USER or HKEY_LOCAL_MACHINEHKEY_CURRENT_USER or HKEY_CLASSES_ROOT as the subkey

5.1.15. restore

Reads the registry information in a specified file and copies it over the specified key. This registry information may be in the form of a key and multiple levels of subkeys
Syntax
RegistryObject:restore(str_newfile)
Arguments
str_newfile
The name of a file that has registration information. This file must have been created with the save function. Under the file allocation table (FAT) file system, the filename may not have an extension.
Returns
SuccessReference to RegistryObject it self
Failurenil.

5.1.16. save

Saves the registry object's key handle subkeys and values to a new file
Syntax
RegistryObject:save(str_file)
Arguments
str_file
Name of the file to save registry data to. This file cannot already exist. If this filename includes an extension, It cannot be used on file allocation table (FAT) file systems by the load, replace, or restore function.
Returns
SuccessReference to RegistryObject it self
Failurenil.
Example
require"winreg"
hkey = winreg.createkey([[HKCU\Software\PARENTKEY\CHILDKEY]])
hkey:setvalue("VALUE1", "STRING")
hkey:setvalue("VALUE2", 2^31)
hkey:setvalue("VALUE3", {"abcde", "12345", "!@#$%"})
hkey:setvalue("VALUE4", "BINARY", "binary")
hkey:setvalue("VALUE5", "%WINDIR%", "expand_sz")
hkey:save("TESTREGDATA")

5.1.17. setvalue

Stores data in the value field of an open registry key.
Syntax
RegistryObject:setvalue(str_value, var_data, [var_type])
Arguments
str_value
Required string value. The name of the value to set
var_data
Required. Data to be stored with the specified value name. The type of this argument depends on var_type
var_type
Optional. Type of information to be stored as the value's data. This parameter can be one of the following values:

Table 5. Registry Value Data Type

Registry Value Data Type
String ValueInteger ValueDescriptionRequired Lua Value of var_data
"sz"1A null-terminated stringstring
"expand_sz"2A null-terminated string that contains unexpanded references to environment variables, for example "%PATH%"string
"binary"3Binary data in any formstring
"dword"4A 32-bit numbernumber
"multi_sz"7An array of null-terminated stringsstring or table conataining strings

The default value of this argument depends on var_data's type. If var_data is a table the data type will be "multi_sz", only the string value in the table will be retrieve. If var_data is a number the data type will be "dword". If var_data is a string the data type will be "sz".

Returns
SuccessReference to RegistryObject it self
Failurenil.
Example
require"winreg"
hkey = winreg.createkey([[HKCU\Software\PARENTKEY\CHILDKEY]])
hkey:setvalue("VALUE1", "STRING")
hkey:setvalue("VALUE2", 2^31)
hkey:setvalue("VALUE3", {"abcde", "12345", "!@#$%"})
hkey:setvalue("VALUE4", "BINARY", "binary")
hkey:setvalue("VALUE5", "%WINDIR%", "expand_sz")
hkey:close()

hkey = winreg.createkey([[HKCU\Software\PARENTKEY\CHILDKEY]])

value, type = hkey:getvalue("VALUE1")
assert(type == 1 and value == "STRING")

value, type = hkey:getvalue("VALUE2")
assert(type == 4 and value == (2^31))

value, type = hkey:getvalue("VALUE3")
assert(type == 7 and value[1] == "abcde"
and value[2] == "12345" and value[3] == "!@#$%")

value, type = hkey:getvalue("VALUE4")
assert(type == 3 and value == "BINARY")

value, type = hkey:getvalue("VALUE5")
assert(type == 2 and value == "%WINDIR%")

5.1.18. unload

Unloads the specified key and subkeys from the registry.
Syntax
RegistryObject:unload(str_subkey)
Arguments
str_subkey
The name of the subkey to be unloaded. The key referred to by the this parameter must have been created by using the load method.
Returns
SuccessReference to RegistryObject it self
Failurenil.
Remarks

The MS Win32 API documentation implies registry object's key handle must be open using only HKEY_USER or HKEY_LOCAL_MACHINE or \\Computername\HKEY_USER or \\Computername\HKEY_LOCAL_MACHINE as the subkey

This function removes a hive from the registry but does not modify the file containing the registry information. A hive is a discrete body of keys, subkeys, and values that is rooted at the top of the registry hierarchy.
Example
require"winreg"			
hkey = winreg.openkey([[HKLM]])
hkey:unload("PARENTKEY")