Wax Lua script upgrade exercise (2)

Source: Internet
Author: User
Tags ziparchive

Wax Lua script upgrade exercise (1) describes how object-C calculates the product of two values by calling the function in Lua and returns the display.

This article introduces how to download a new Lua script file by clicking the button, and hot-load Lua so that it can take effect immediately.

Make a little preparation before writing code.

1. Start the apache service on the local machine as the storage location of the new Lua script

Open terminal, enter sudo apachectl start (you may need to enter machine secrets), open the address bar of safari and enter 127.0.0.1. The content is "It works !" Page.

It is located under "/Library (resource library)/webserver/documents/", which is the default root directory of Apache.

Create a folder script in this directory and store the new script in this directory.

(Stop: sudo apachectl stop restart: sudo apachectl restart)


2. Download The third-party library ziparchive. Decompress the script file obtained from the network.

Set ziparchive. m, ziparchive. h, crypt. h, ioapi. c, ioapi. h, mztools. c, mztools. h, unzip. c, unzip. h, zip. c, zip. load the H file to the project.

Option + command + A add the file to the project, select copy items into destination group's folder, and click Add.

At this time, running the program may report an error because some files do not support arc. Method:

(Project-> taggets-> build phases, you can see that compile sources contains the class. M file in your project. Double-click the file you do not use arc and enter-fno-objc-arc)


Then start writing the code.
The function (ibaction) downlodnewlua (ID) corresponding to the "download new script" button must add the following code to the sender:
- (IBAction)downlodNewLua:(id)sender {    [[luaMain shareInstance] ExecLua:@{@"cmd":LUA_EVENT_DOWNLOAD_NEN_SCRIPT, @"param":@{}}];}



Add a new luacallbak class for Lua to call OC code to the interface

Luacallbak. m

#import "luaCallBak.h"@implementation luaCallBak+ (luaCallBak*) shareInstance{    static luaCallBak* _this = nil;        static dispatch_once_t onceTokenInit;    dispatch_once(&onceTokenInit, ^{        _this = [[luaCallBak alloc] init];    });        return _this;} - (NSString *) temdir{   NSString * tem= NSTemporaryDirectory();    return tem;}- (NSString * )DocumentsDir{   return  [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];}@end


Modify the exeluacode function of the Main. Lua File
Function exeluacode (PARAM) -- bodyprint ('exeluacode') if (not PARAM) thenreturn nil; endlocal dict_param = wax. JSON. parse (PARAM); If dict_param thenlocal cmd = dict_param ['cmd']; If cmd = '000000' thenreturn multiply (dict_param ['param']) elseif cmd = '000000' then updatescriptstatus () -- download the new script endendend



Add the following content at the end of the main. Lua file:
Local script_url = 'HTTP: // 192.168.1.102/script/new_script.zip '; -- network address of the new script file function updatescriptstatus () -- bodywax. HTTP. request {script_url, format = 'binary ', callback = function (retvalue, retresponse) -- bodylocal ret_obj2 = retvalue; -- the binary file downloaded from the network address if retresponse and retresponse: statuscode () = 200 and ret_obj2 thenprintlog ('start unzip') if not scriptunzip (ret_obj2) then -- decompress the binary file and return; Endprintlog ('start move script') if not movetemscripttoscript () then -- move the new script to a fixed position return; endreload_script_files (); -- load the new script elseprintlog ('request err ') endend} endfunction scriptunzip (zipdata) -- bodylocal tmp_dir = luacallbak: Using instance (): temdir (); -- call the temdir function of OC, obtain the temporary path for storing temporary files: Local tempath = tmp_dir .. '/video_analyze_script'; Local scriptupdatedir = tmp_dirlocal zipfile = scriptupdatedir .. '/download_v Ideo_analyze_script '; zipdata: writetofile_atomically (zipfile, 0); -- write binary content in the memory as a temporary file local bexist = nsfilemanager: defaultmanager (): fileexistsatpath (zipfile ); -- check whether the file is successfully written if not bexist thenprintlog ('zipfile failed'); return; end -- unzip file unzip the file to the tempath directory local ziparchine = ziparchive: Init (); if not ziparchine thenprintlog ('ziparchine nill'); return; endif not ziparchine: unzipopenfile (zipfile) thenprintlog ('o Pen ZIP file failed '); return; endif not ziparchine: unzipfileto_overwrite (tempath, 1) thenprintlog ('unzip file failed'); return; endziparchine: unzipclosefile (); return 1end -- the Mobile Script is so complicated that it prevents errors during script moving. Function movetemscripttoscript () -- body -- printlog ('movetemscripttoscript') Local scriptdir = luacallbak: Invalid instance (): documentsdir (); -- scriptdir stores the script path after upgrade. scriptdir = scriptdir .. '/video_analyze_script' Local tmp_dir = luacallbak: Using instance (): temdir (); Local tempath = tmp_dir .. '/video_analyze_script'; Local backscriptdir = tempath .. '_ Bak'; local FM = nsfilemanager: defaultmanager (); Local B = Nil; Local bexist = nsfilemanager: defaultmanager (): fileexistsatpath (scriptdir); -- check whether the script printlog (scriptdir) printlog (bexist) if not bexist thenb = FM: moveitematpath_topath_error (tempath, scriptdir, nil); -- no script is available. Move the downloaded file to the scriptdir location elsefm: removeitematpath_error (backscriptdir, nil ); -- remove the folder B = FM: moveitematpath_topath_error (scriptdir, backscriptdir, nil) for backup of existing scripts; -- change the folder name to if B then B = FM: Mo Veitematpath_topath_error (tempath, scriptdir, nil); -- move the downloaded and decompressed file to the scriptdir location if B then Fm: removeitematpath_error (backscriptdir, nil); -- moved successfully, remove existing scripts to the backup folder printlog ('remove old scriptdir') elsefm: moveitematpath_topath_error (backscriptdir, scriptdir, nil); -- failed to move, change the existing script to the backup folder to the existing script folder name end endendreturn bendfunction reload_script_files (...) -- body printlog ("[reload_script_files...] ") Local scriptdir = luacall Bak: Initialize instance (): documentsdir (); -- call the OC Function to obtain the sources file path, used to store the new script scriptdir = scriptdir .. '/video_analyze_script' -- sets Lua to the environment variable. When a new require script is run, use local m_package_path = package. path printlog (m_package_path) if not string. find (m_package_path, 'video _ analyze_script ') thenpackage. path = string. format ("% S /?. Lua ", scriptdir) endprintlog (package. path) package. loaded ['main'] = nil require ('main') printlog ("[reload_script_files... done] ") Return" reload OK "End

The Code has been added. After you click to download the new script, the function call process is

Downlodnewlua-execlua-exeluacode-updatescriptstatus-scriptunzip-movetemscripttoscript-reload_script_files


Compress main.lua into a zip file, rename new_script.zip, and store it in the local/library/webserver/documents/Script directory.

Change "*" in the multiply function in the main. Lua file to "+" to run the program.

Click "4*3 =", output 7, log Printing

exeLuaCodemultiplyMultiplicand = 4Multiplier = 37

Click "download new script" to print logs.

exeLuaCodestart UnZip2014-08-02 21:36:39.820 WaxDemo[16316:60b] 1 entries in the zip filestart move Script/Users/zhaoyan/Library/Application Support/iPhone Simulator/7.1/Applications/DCA2AC15-6DE7-4393-9565-345A182906E6/Documents/video_analyze_scripttrueremove old ScriptDir[reload_script_files...]scripts/?.lua;scripts/?/init.lua;scripts/?.dat;?.lua;?/init.lua;?.dat;/Users/zhaoyan/Library/Application Support/iPhone Simulator/7.1/Applications/DCA2AC15-6DE7-4393-9565-345A182906E6/Documents/video_analyze_script/?.lua[reload_script_files...done]

Click "4*3 =" again, OUTPUT 12, log Printing

exeLuaCodemultiplyMultiplicand = 4Multiplier = 312

Successful !!!


The problem is not solved. After the program is re-opened, the old script is loaded, that is, when the program is closed and the program is re-opened, click "4*3 =, the output is still 7.





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.