How to write a double value byte by byte - lua

I have to communicate with a dll and it lua and this is the function I use to write strings by bytes:
writeString = function(pid, process, address, value)
local i = 1
while i <= String.Length(value) do
local byte = string.byte(value, i, i)
DLL.CallFunction("hook.dll", "writeMemByte", pid..','..process..','..address + (i-1)..','..byte, DLL_RETURN_TYPE_INTEGER, DLL_CALL_CDECL)
i = i + 1
end
DLL.CallFunction("hook.dll", "writeMemByte", pid..','..process..','..address + (i-1)..',0', DLL_RETURN_TYPE_INTEGER, DLL_CALL_CDECL)
end
I basically need to adapt this to write a double value byte by byte.
I just can't think how to make the memory.writeDouble function.
EDIT: this is my readString function:
readString = function(pid, process, address)
local i, str = 0, ""
repeat
local curByte = DLL.CallFunction("hook.dll", "readMemByte", pid..','..process..','..(address + i), DLL_RETURN_TYPE_INTEGER, DLL_CALL_CDECL)
if curByte == "" then curByte = 0 end
curByte = tonumber(curByte)
str = str .. string.char(curByte)
i = i + 1
until (curByte == 0)
return str
end,

My first recommendation would be: try to find a function that accepts strings representing doubles instead of doubles. Implementing the lua side of that would be incredibly easy, since you already have a writeString - it could be something very similar to this:
writeDouble = function(pid, process, address, value)
writeString(pid, process, address, tostring(value))
end
If you don't have that function, but you have access to the dll source, you can try to add that function yourself; it shouldn't be much more complicated than getting the string and then calling atof on it.
If you really can't modify the dll, then you need to figure out the exact double format that the lib is expecting - there are lots of factors that can change that format. The language and compiler used, the operative systems, and the compiler flags, to cite some.
If the dll uses a standard format, like IEE-754, the format will usually have well documented "translations" from/two bites. Otherwise, it's possible that you'll have to develop them yourself.
Regards and good luck!

There are many libraries available for Lua that do just this.
If you need the resulting byte array (string), string.pack should do it; you can find precompiled binaries for Windows included with Lua for Windows.
If you are more interested in using the double to interface with foreign code, I would recommend taking a different approach using alien, a Foreign Function Interface library that lets you directly call C functions.
If you able to, I even more highly recommend switching to LuaJIT, a Just-In-Time compiler for Lua that provides the power, speed and reach of C and assembly, but with the comfort an flexibility of Lua.
If none of these solutions are viable, I can supply some code to serialise doubles (not accessible at the moment).

Related

Should parameters be used as variables in Lua?

I've been told in Java that I should avoid modifying the original parameters such as
public int doStuff(int begin, int end) {
/* loop or something */
begin++; //bad
end--; //also bad
/* end loop */
return
}
instead, I should do something like
public int doStuff(int begin, int end) {
int myBegin = begin; //something like this
int myEnd = end;
/* stuff */
return
}
So, I've been doing this in lua
function do_stuff(begin, last)
local my_begin = begin
local my_last = last
--stuff
my_begin = my_begin + 1
my_last = my_last - 1
--stuff
end
But, I'm wondering if
function do_stuff(begin, last)
--stuff
begin = begin + 1
last = last - 1
--stuff
end
is also discouraged, or is it nice and concise?
There are no rules. Let taste, clarity, and need decide.
Nevetheless, a common idiom is to provide default values for parameters as in
function log(x,b)
b = b or 10
...
end
If you were told not to modify the parameters of functions, then there was probably a reasoning associated with that. Whatever that reasoning is would apply as much to Lua as to Java, since they have similar function argument semantics. Those reasons could be one or more of (but not limited to):
If you modify a parameter... you don't have it anymore. If you suddenly have a need for the original value you were passed, it's gone now.
Creating confusion, depending on how the parameters are named. The word "begin" suggests the beginning of something. If you change it, it isn't necessarily the beginning anymore, but merely the current element you're operating on.
Creating potential errors, if dealing with reference types (non-basic types in Java, tables and such in Lua). When you modify an object, you're changing it for everyone. Whereas incrementing an integer is just changing your local value. So if you're frequently modifying parameters, you still need to think about which ones you ought to be poking at and which ones you shouldn't be.
To put it another way, if you agreed with the suggestion for doing so in Java, then it applies just as much to Lua. If you didn't agree with the suggestion in Java, then you have no more reason to follow it under Lua.
In Lua functions, threads, tables and userdata types are passed by reference. So unless you have one of those you are working with a local copy anyway.
So in your example:
function do_stuff(begin, last)
--stuff
begin = begin + 1
last = last - 1
--stuff
end
begin and last are local non-reference variables in do_stuff's scope.
The only reason to make a copy of them is that you might want to store there initial value for later use. For that purpose you can either create a backup copy of the initial value or you create a working copy of it. Whatever you prefer.
Only make sure you know what is passed by reference and what by value so you avoid changing things you don't want to change and the other way around.

Lua: Working with the Modbus TCP/IP Protocol

This question is based off a previous question I asked concerning a similar topic: Lua: Working with Bit32 Library to Change States of I/O's . I'm trying to use a Lua program that, when a PLC changes the state of a coil at a given address (only two addresses will be used) then it triggers a reaction in another piece of equipment. I have some code that is basically the exact same as my previous topic. But this has to do with what this code is actually doing and not so much the bit32 library. Usually I run code I don't in understand in my Linux IDE and slowly make changes until I finally can make sense of it. But this is producing some weird reactions that I can't make sense of.
Code example:
local unitId = 1
local funcCodes = {
readCoil = 1,
readInput = 2,
readHoldingReg = 3,
readInputReg = 4,
writeCoil = 5,
presetSingleReg = 6,
writeMultipleCoils = 15,
presetMultipleReg = 16
}
local function toTwoByte(value)
return string.char(value / 255, value % 255)
end
local coil = 1
local function readCoil(s, coil)
local req = toTwoByte(0) .. toTwoByte(0) .. toTwoByte(6) .. string.char(unitId, funcCodes.readCoil) .. toTwoByte(coil - 1) .. toTwoByte(1)
s:write(req) --(s is the address of the I/O module)
local res = s:read(10)
return res:byte(10) == 1 -- returns true or false if the 10th bit is ==1 I think??? Please confirm
end
The line that sets local req is the part I'm truly not making sense of. Because of my earlier post, I understand fully about the toTwoByte function and was quickly refreshed on bits & byte manipulation (truly excellent by the way). But that particular string is the reason for this confusion. If I run this in the demo at lua.org I get back an error "lua number has no integer representation". If I separate it into the following I am given back ascii characters that represent those numbers (which I know string.char returns the ascii representation of a given digit). If I run this in my Linux IDE, it displays a bunch of boxes, each containing four digits; two on top of the other two. Now it is very hard to distinguish all of the boxes and their content as they are overlapping.
I know that there is a modbus library that I may be able to use. But I would much rather prefer to understand this as I'm fairly new to programming in general.
Why do I receive different returned results from Windows vs Linux?
What would that string "local req" look like when built at this point to the I/O module. And I don't understand how this req variable translates into the proper string that contains all of the information used to read/write to a given coil or register.
If anyone needs better examples or has further questions that I need to answer, please let me know.
Cheers!
ETA: This is with the Modbus TCP/IP Protocol, not RTU. Sorry.

matlab indexing into nameless matrix [duplicate]

For example, if I want to read the middle value from magic(5), I can do so like this:
M = magic(5);
value = M(3,3);
to get value == 13. I'd like to be able to do something like one of these:
value = magic(5)(3,3);
value = (magic(5))(3,3);
to dispense with the intermediate variable. However, MATLAB complains about Unbalanced or unexpected parenthesis or bracket on the first parenthesis before the 3.
Is it possible to read values from an array/matrix without first assigning it to a variable?
It actually is possible to do what you want, but you have to use the functional form of the indexing operator. When you perform an indexing operation using (), you are actually making a call to the subsref function. So, even though you can't do this:
value = magic(5)(3, 3);
You can do this:
value = subsref(magic(5), struct('type', '()', 'subs', {{3, 3}}));
Ugly, but possible. ;)
In general, you just have to change the indexing step to a function call so you don't have two sets of parentheses immediately following one another. Another way to do this would be to define your own anonymous function to do the subscripted indexing. For example:
subindex = #(A, r, c) A(r, c); % An anonymous function for 2-D indexing
value = subindex(magic(5), 3, 3); % Use the function to index the matrix
However, when all is said and done the temporary local variable solution is much more readable, and definitely what I would suggest.
There was just good blog post on Loren on the Art of Matlab a couple days ago with a couple gems that might help. In particular, using helper functions like:
paren = #(x, varargin) x(varargin{:});
curly = #(x, varargin) x{varargin{:}};
where paren() can be used like
paren(magic(5), 3, 3);
would return
ans = 16
I would also surmise that this will be faster than gnovice's answer, but I haven't checked (Use the profiler!!!). That being said, you also have to include these function definitions somewhere. I personally have made them independent functions in my path, because they are super useful.
These functions and others are now available in the Functional Programming Constructs add-on which is available through the MATLAB Add-On Explorer or on the File Exchange.
How do you feel about using undocumented features:
>> builtin('_paren', magic(5), 3, 3) %# M(3,3)
ans =
13
or for cell arrays:
>> builtin('_brace', num2cell(magic(5)), 3, 3) %# C{3,3}
ans =
13
Just like magic :)
UPDATE:
Bad news, the above hack doesn't work anymore in R2015b! That's fine, it was undocumented functionality and we cannot rely on it as a supported feature :)
For those wondering where to find this type of thing, look in the folder fullfile(matlabroot,'bin','registry'). There's a bunch of XML files there that list all kinds of goodies. Be warned that calling some of these functions directly can easily crash your MATLAB session.
At least in MATLAB 2013a you can use getfield like:
a=rand(5);
getfield(a,{1,2}) % etc
to get the element at (1,2)
unfortunately syntax like magic(5)(3,3) is not supported by matlab. you need to use temporary intermediate variables. you can free up the memory after use, e.g.
tmp = magic(3);
myVar = tmp(3,3);
clear tmp
Note that if you compare running times with the standard way (asign the result and then access entries), they are exactly the same.
subs=#(M,i,j) M(i,j);
>> for nit=1:10;tic;subs(magic(100),1:10,1:10);tlap(nit)=toc;end;mean(tlap)
ans =
0.0103
>> for nit=1:10,tic;M=magic(100); M(1:10,1:10);tlap(nit)=toc;end;mean(tlap)
ans =
0.0101
To my opinion, the bottom line is : MATLAB does not have pointers, you have to live with it.
It could be more simple if you make a new function:
function [ element ] = getElem( matrix, index1, index2 )
element = matrix(index1, index2);
end
and then use it:
value = getElem(magic(5), 3, 3);
Your initial notation is the most concise way to do this:
M = magic(5); %create
value = M(3,3); % extract useful data
clear M; %free memory
If you are doing this in a loop you can just reassign M every time and ignore the clear statement as well.
To complement Amro's answer, you can use feval instead of builtin. There is no difference, really, unless you try to overload the operator function:
BUILTIN(...) is the same as FEVAL(...) except that it will call the
original built-in version of the function even if an overloaded one
exists (for this to work, you must never overload
BUILTIN).
>> feval('_paren', magic(5), 3, 3) % M(3,3)
ans =
13
>> feval('_brace', num2cell(magic(5)), 3, 3) % C{3,3}
ans =
13
What's interesting is that feval seems to be just a tiny bit quicker than builtin (by ~3.5%), at least in Matlab 2013b, which is weird given that feval needs to check if the function is overloaded, unlike builtin:
>> tic; for i=1:1e6, feval('_paren', magic(5), 3, 3); end; toc;
Elapsed time is 49.904117 seconds.
>> tic; for i=1:1e6, builtin('_paren', magic(5), 3, 3); end; toc;
Elapsed time is 51.485339 seconds.

Lua Alien Module - Trouble using WriteProcessMemory function, unsure on types (unit32)

require "alien"
--the address im trying to edit in the Mahjong game on Win7
local SCOREREF = 0x0744D554
--this should give me full access to the process
local ACCESS = 0x001F0FFF
--this is my process ID for my open window of Mahjong
local PID = 1136
--function to open proc
local op = alien.Kernel32.OpenProcess
op:types{ ret = "pointer", abi = "stdcall"; "int", "int", "int"}
--function to write to proc mem
local wm = alien.Kernel32.WriteProcessMemory
wm:types{ ret = "long", abi = "stdcall"; "pointer", "pointer", "pointer", "long", "pointer" }
local pRef = op(ACCESS, true, PID)
local buf = alien.buffer("99")
-- ptr,uint32,byte arr (no idea what to make this),int, ptr
print( wm( pRef, SCOREREF, buf, 4, nil))
--prints 1 if success, 0 if failed
So that is my code. I am not even sure if I have the types set correctly.
I am completely lost and need some guidance. I really wish there was more online help/documentation for alien, it confuses my poor brain.
What utterly baffles me is that it WriteProcessMemory will sometimes complete successfully (though it does nothing at all, to my knowledge) and will also sometimes fail to complete successfully. As I've stated, my brain hurts.
Any help appreciated.
It looks like your buffer contains only 2 bytes ("99"), but you specify 4 bytes in the call to WriteProcessMemory.
If your intention was to write the 32-bit value 99 into memory (as a number, not an ASCII string), you can use:
alien.buffer("\99\0\0\0")
You can convert arbitrary integers to string representations using alien.struct.pack:
require "alien.struct"
s = alien.struct.pack('i', 99)
buf = alien.buffer(s)
I know this question is long forgotten, but I ran into the same issue (with the same function), and there was nothing on the web except this question, and then I solved it myself, so I'm leaving my solution here.
SHORT ANSWER
The type of the second argument of WriteProcessMemory is not "pointer". I mean, officially it is, but alien cannot cast a raw address to a "pointer", so you are better off pretending it's a "long" instead. So your types declaration should look like
wm:types{ ret = "long", abi = "stdcall"; "pointer", "long", "pointer", "long", "pointer" }
LONG ANSWER
I was playing around with ReadProcessMemory, since I figured that before writing something you need to verify that this something actually exists. So one time I called ReadProcessMemory, and it returned a buffer that wasn't what I was looking for, but it wasn't empty either. In fact, it seemed something was written there - as in, an ASCII string. Not text, though, just some digits. But that was enough to convince me that the data actually came from somewhere.
So I grabbed Cheat Engine, opened the same process and ran a search for this string. And guess what - it actually was there, but the address was completely wrong. That led me to believe that the address is specified wrongly. After trying to find a way to generate a "pointer" object from a Lua number, I gave up and changed the types declaration - after all, a pointer is just a differently interpreted integer.
After all that, I did some investigating, including reading the sources of both lua and alien, and stepping through the relevant parts with a debugger. It turns out, the full walkthrough of the error is as follows:
The "pointer" keyword has special behaviour for strings: if your "pointer"-declared argument is actually a Lua string, then a new buffer is instantly created, the string is copied there, and it is used as the real argument.
Alien uses the lua_isstring function to implement this
lua_isstring returns "true" not only for actual strings, but for numbers as well, since they are auto-convertible into strings.
As a result, your SCOREREF is turned into a string, copied into a newly created buffer, and the address of THAT is passed into WriteProcessMemory as a void*.
Since the layouts of most processes in their respective address spaces are similar, this void* more often than not happens to coincide with an address of some thing or another in the target process. That is why the system call sometimes succeedes, it just writes into a completely wrong place.

Embedding Lua in OCaml

Could you, please, give a code snippet showing how to use Lua embedded in OCaml?
A simple example could be a "Hello, World" variant. Have OCaml prompt the user for a name. Then pass that name to a Lua function. Have Lua print a greeting and return the length of the name. Then have OCaml print a message about the length of the name.
Example:
user#desktop:~$ ./hello.opt
Name? User
Hello, User.
Your name is 4 letters long.
user#desktop:~$
[Edit]
As a non-C programmer, could I implement this without having to write an intermediary C program to pass the data between Lua and OCaml?
Following is a theoretical idea of what I would like to try. Unfortunately, line 3 of ocaml_hello.ml would need to know how to call the function defined in lua_hello.lua in order for the code to be valid.
lua_hello.lua
Defines lua_hello, which prints an argument and returns its length.
1 function lua_hello (name)
2 print ("Hello, "..name..".")
3 return (string.len (name))
4 end
ocaml_hello.ml
OCaml prompts for a name, calls the Lua function, and prints the return value.
1 let () = print_string "Name? "; flush stdout in
2 let name = input_line stdin in
3 let len = Lua_hello.lua_hello name in
4 Printf.printf "Your name is %d letters long." len; flush stdout;;
I'm not aware of a mature set of bindings for embedding the C implementation of Lua into OCaml. An immature set of bindings was posted on the Caml mailing list in 2004.
If you want to use the ML implementation you can find some examples in a paper called ML Module Mania. The ML implementation, unlike the C implementation, guarantees type safety, but to do so it uses some very scurvy tricks in the ML module system. If you are asking basic questions, you probably want to avoid this.
In your example it's a little hard to guess where you want the function to come from. I suggest you either ask for a C example or give people a C example and ask how it could be realized in OCaml (though I think bindings are going to be a problem).
Edit
In response to the revised question, it's pretty complicated. The usual model is that you would put Lua in charge, and you would call Objective Caml code from Lua. You're putting Caml in charge, which makes things more complicated. Here's a rough sketch of what things might look like:
let lua = Lua.new() (* create Lua interpreter *)
let chunk = LuaL.loadfile lua "hello.lua" (* load and compile the file hello.lua *)
let _ = Lua.call lua 0 0 (* run the code to create the hello function *)
let lua_len s =
(* push the function; push the arg; call; grab the result; pop it; return *)
let _ = Lua.getglobal lua "lua_hello" in
let _ = Lua.pushstring lua s in
let _ = Lua.call lua 1 1 in
let len = Lua.tointeger lua (-1) in
let _ = Lua.pop lua 1 in
len
let () = print_string "Name? "; flush stdout
let name = input_line stdin
let len = lua_len name
Printf.printf "Your name is %d letters long." len; flush stdout;;
Again, I don't know where you'll get the bindings for the Lua and LuaL modules.
On further reflection, I'm not sure if you can do this with the official C implementation of Lua, because I think OCaml believes it owns main(). You'd have to find out if OCaml could be packaged as a library from a C main program.
For an example of putting Lua-ML in charge, you can get Lua-ML standalone from Cminusminus.org, and you can also check out the examples in the paper on Lua-ML as well as the source code to the QC-- compiler itself.

Resources