Access objects through Lua (iPhone SDK) - iphone

I'm trying to get to grips with how Lua works, and how it can be integrated into a project, like an Obj-C based iPhone game. I've got Lua's source integrated fine, and have managed to use a simple manager class to translate function calls written in a .lua file, to Obj-C methods in the project.
I'm now a little stuck; I'm not sure how to go about what I'd like to use Lua for, and having Googled a lot on it I haven't found an article which fills the little gaps in my understanding. What I'd like to do is use Lua to script simple game logic for levels in my game; for example, I might want to check that the player has moved to a certain part of the level, then once he does that I check if he picks up an object, then once he throws that object I check if it hits another object, etc, etc.
In the script, I'd like to have something like this:
if (objectsAreTouching(level.objects["objIndex1"], level.objects["objIndex2"]))
{
//Move to next win-condition.
}
So I know how to access a function, for example the one named above, objectsAreTouching, but I can't see how I would, from within the .lua file, access a Dictionary or Array from within one of the game's main classes. I assume this must be possible, am I right? If so, how do you do this? If you can, can you then have a method in your game engine which returns a BOOL pass that return value to the script, so that the if statement above would then execute the code within it?
I may well have asked this question badly, and so if I need to clarify anything let me know. Also, I'm aware of the issues surrounding Apple's ban of interpreted code, and it doesn't concern me for this little project.
Thanks for any help!

You have (at least) three options:
Create the Dictionary (using a Lua table) and Array (also using a Lua table) on the Lua side rather than on the C++ side; you can do this in C++ using Lua's C API, or in a Lua script that you load to construct the game environment.
Provide access functions to Lua to read the C++ based Dictionary and Array. These access functions are just like the objectsAreTouching function you described, but at the level of data accessors. Typically the results returned from the accessors would be lightuserdata.
Use Lua userdata objects to share the state of the Dictionary and Array between Lua and C++. In this case they would be C++ objects requiring accessors, just like (2), but would be managed by Lua and could have methods (a metatable) and an environment associated with them.

Related

How to call Python functions from DML?

I would like to have a DML device with interfaces and register banks as the TOP-level of my device but offload processing to Python. Is there a lightweight method of calling into Python from DML?
This post How can I unit test a specific DML method? addresses calling from Python into DML, but I am interested in the reverse.
I think I can create a bunch of custom interfaces to do this, but I'm interested to know if there's a better way.
Implementing parts of a device in Python can make sense, in particular for code that seldom is invoked (user interaction comes to mind), and when faced with tasks like string manipulation where the shortcomings of a C-like language is particularly painful, or when code sharing with CLI commands is desired.
You can use the SIM_call_python_function API to call out to Python from DML. The function uses the equivalent of eval on the passed string, so you can find a module-local function by __import__:
local attr_value_t a = SIM_make_attr_list(0);
local attr_value_t result = SIM_call_python_function(
"__import__('simics').SIM_version", &a);
log info: "%s", SIM_attr_string(result);
SIM_attr_free(&a);
SIM_attr_free(&result);
This API is admittedly not very pretty. Parts of the standard lib for DML 1.2 is in fact written in Python and uses the internal function VT_call_python_module_function for this task instead. That API is nicer, but we cannot recommend use of VT_ functions outside the core Simics team.
This question is really more about the Simics simulator framework than about DML. Given how Simics works, Python code lives in a separate context. There is no obvious light-weight way. Rather, you need to put the Python code in a separate Python class and a separate runtime object and use a Simics simulator interface to orchestrate the calling.
The Python code would in general not be able to access the state of the object anyway, so it would have to be a strict "compute this and return all computed values". Which is not very convenient for device behavior that is really all about mutating the state of the object.
Even with a bunch of interfaces, there is still the matter of state handling. I guess you need an interface for that as well.

Can I use Swift on the back end of an API?

I am wanting to create a chess engine. I am most familiar with Swift, and super high-performance isn't all that important to me (otherwise I'd likely learn and write it in C++). I need my engine to take in a chess position in an FEN formatted string, which would look something like this: rnbqkbnr/pp1ppppp/8/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2. It would then process the position and spit out a move in algebraic notation, like Nxd4.
These specifics aren't all that important, however, as I can program all of this in Swift. What I am wondering is how one would create an API with swift to do this. That is, the url encoded FEN position is passed a parameter to the API like so: https://www.mywebsite.com/chessEngine?position=rnbqkbnr%2Fpp1ppppp%2F8%2F2p5%2F4P3%2F5N2%2FPPPP1PPP%2FRNBQKB1R%20b%20KQkq%20-%201%202
The Swift code would then process this position on the backend, and the response would be something like:
{status:"success",recommendedMove:"Nxd4",moveTime:"12.34"}
Is it even possible to have Swift code process on the back end? My API development experience is limited to taking parameters as url parameters, making an SQL query, and then echoing the query response as a JSON.
See also: https://chess.stackexchange.com/questions/26489/creating-chess-engine-machine-learning-vs-traditional-engine
Yes, it is possible. Although I haven't built a full site/API with Swift, I know that Vapor uses itself to host its website, and my (albeit limited) experience with it suggests that it would be a good pick. That said, you could also use Kitura or Perfect — try looking up a comparison between them.
Good luck!

Organizing Session Vars in Scala/Lift

Would like to get some thoughts on how to best organize session vars within a scala / lift application.
I've read over a number of scala materials online and have found generally the following paradigm in all examples that introduce session vars:
declare an object that extends the SessionVar class
put that object into a file that contains a snippet (or any file)
access that object from anywhere in the codebase (lift will take care of the session var's lifecycle based on the lifetime of the user's http session)
Perhaps I'm not understanding something, but I'm concerned that this approach would lead to a whole bunch of these objects in various files all over the place. Its not such a big deal if its a small app, but when a project gets larger this could lead to chaos.
For those who have worked on larger scala projects, is there a generally accepted better approach? (even if its something simple like putting all of these objects into a common file?)
Thanks.
This is a bit subjective, but I'll give it a try. I think it depends on the scope the session var has in your project.
If you need the session var only in one snippet, you should make it a private member of that class.
If you need it in several but not all snippets, put those snippets in a package and make the object private to that package. If you have a lot of them, you could create an extra file to hold them.
If you need it globally, put it into a central location, maybe inside a package object.
If possible, avoid using SessionVars completely.
SessionVars should be used sparingly in your application. They are similar to Servlet Session Variables, except they are type safe.
How many session variables do you need? Personally, I have a session variable for the primary key of the current user and maybe one or two more. The rest of the state of the application should be stored in closures (because functions associated with GUIDs close over scope).

iPhone SDK function/method with arguments

I'm creating an app in which I do the same thing multiple times. I'm going for as little code as possible and I don't want to repeat myself.
I need the PHP equivalant of a reusable function, where I set an input, and the function will return the output.
The app is a URL shortener, so the input as you may assume is a URL, and the output is the short URL.
What's the best way to go about this? I know I can code the same thing twice, but I hate to repeat myself.
Hopefully I'm getting my point across. Any help is greatly appreciated.
-Giles
Apologies if I'm oversimplifying your question, but are you asking how to define an Objective-C method? If so, you're going to have to learn Objective-C, there's no way around it:
The Objective-C Programming Language - Object Messaging
You can do a lot of great things with no code on the iPhone and Mac platforms, but it's hard to imagine completing any useful application without writing some code.
Example
- (float)multiplyThisFloatByTwoPointFive:(float)numberToMultiply
{
return numberToMultiply * 2.5;
}
To call it:
[self multiplyThisFloatByTwoPointFive:3.7];
Libraries
If you mean "I want to put these non-class-specific methods somewhere I can access them universally", eg, a library, you can do this in two ways:
Create some sort of "library" class like "MySpecialMathClass" (not to be confused with "my special education math class") or "MyAppAnimationTricks" and put your methods there (you'd define them as +someMethod: not -someMethod:, class- not instance-method, per Objective-C).
If they only ever deal with primitives (such as int, float, double ...), consider just making them C functions, rather than Objective-C methods.
I am pretty much a newbie at this, but you can certainly write functions (as opposed to methods) in Objective C.
I wrote several utility functions recently. I created an NSObject file to place them in, but it has no ivars or methods declared, just the functions. Then implement the functions in the .m file, and import the .h file into any class file where you want the functions. You can obviously call these from anywhere in any .m file that has imported the function file.
John Doner

Does it matter if there are unused functions I put into a big CoolFunctions.h / CoolFunctions.m file that's included everywhere in my project?

I want to create a big file for all cool functions I find somehow reusable and useful, and put them all into that single file. Well, for the beginning I don't have many, so it's not worth thinking much about making several files, I guess. I would use pragma marks to separate them visually.
But the question: Would those unused methods bother in any way? Would my application explode or have less performance? Or is the compiler / linker clever enough to know that function A and B are not needed, and thus does not copy their "code" into my resulting app?
This sounds like an absolute architectural and maintenance nightmare. As a matter of practice, you should never make a huge blob file with a random set of methods you find useful. Add the methods to the appropriate classes or categories. See here for information on the blob anti-pattern, which is what you are doing here.
To directly answer your question: no, methods that are never called will not affect the performance of your app.
No, they won't directly affect your app. Keep in mind though, all that unused code is going to make your functions file harder to read and maintain. Plus, writing functions you're not actually using at the moment makes it easy to introduce bugs that aren't going to become apparent until much later on when you start using those functions, which can be very confusing because you've forgotten how they're written and will probably assume they're correct because you haven't touched them in so long.
Also, in an object oriented language like Objective-C global functions should really only be used for exceptional, very reusable cases. In most instances, you should be writing methods in classes instead. I might have one or two global functions in my apps, usually related to debugging, but typically nothing else.
So no, it's not going to hurt anything, but I'd still avoid it and focus on writing the code you need now, at this very moment.
The code would still be compiled and linked into the project, it just wouldn't be used by your code, meaning your resultant executable will be larger.
I'd probably split the functions into seperate files, depending on the common areas they are to address, so I'd have a library of image functions separate from a library of string manipulation functions, then include whichever are pertinent to the project in hand.
I don't think having unused functions in the .h file will hurt you in any way. If you compile all the corresponding .m files containing the unused functions in your build target, then you will end up making a bigger executable than is required. Same goes for if you include the code via static libraries.
If you do use a function but you didn't include the right .m file or library, then you'll get a link error.