@ddabrahim just for academic interest, you can obfuscate code with string.dump(f) to encode a function* into a string, then use loadstring(bytecode) to load the encoded string of that function back into a Lua function.
* From the Lua manual (and I just tested, the LuaJIT runtime that Löve uses also follows this rule), the function cannot access any external local variables because their value will be 'nil'. It can reference globals (variables defined without the 'local' keyword), and receive paramteres, but not access local variables defined outside of that function. So if you need any external data inside that function that is not a global, you should send it in as function parameters.
Anyway, string.dump will "obfuscate" the function code into a string. We can clean the string so that you can later reuse it inline with your other Lua code, like this:
Code: Select all
-- Function whose code I want to hide:
local function passwordFunction(seed)
return seed * 2 + 1
end
-- Get the bytecode string of that function and make it into something that we can copy-paste on another Lua source file.
local bytecode = string.dump(passwordFunction, true)
bytecodeTable = {string.byte(bytecode, 1, -1)}
local intToHex = {}
for v = 0, 255 do
intToHex[tostring(v)] = string.format('x%02X', v)
end
-- Transform the list of bytes into a string where each byte is replaced with a hex-escaped character.
-- That is, a byte of value 128 will become string "\\x80".
local cleanBytecode = ('\\' .. table.concat(bytecodeTable, '\\')):gsub('%d+', intToHex)
-- Write to some temporary file.
local file = io.open('C:/bytecode.txt', 'w')
file:write(cleanBytecode)
file:close()
The result is a file with a sequence of hex-escaped characters.
You can copy the contents of that file as an inline string on your Lua code, like this:
Code: Select all
local inlineBytecode = '\x1B\x4C\x4A\x02\x0A\x15\x00\x01\x02\x00\x00\x02\x03\x18\x01\x00\x00\x16\x01\x01\x01\x4C\x01\x02\x00\x04\x02\x00'
local restoredPasswordFunction = loadstring(inlineBytecode)
print(restoredPasswordFunction(7)) -- Outputs 15.
My opinion?
It's absolutely not worth the effort.
You need to think about the real reasons why you don't want people seeing your code or assets, and try to look at it from a different perspective: I don't remember any instance of assets being used to the detriment of the sales & success of a popular game. On the contrary -- that players are able to peek inside the code and assets might give your game an afterlife with modding, user patches etc and basically be free marketing.