尝试在delphi开发过程中使用LUA进行扩展

Filed under: 程序开发 |
Posted on

使用的是 for delphi扩展,文件共有5个,一个dll,4个pas。
lua版本是5.0.2,可以点击这里下载。
写了一个简单的demo,delphi主程序完成对lua扩展的加载,同时对用户输入的日期以及当前日期进行比较,lua文件完成对比较结果的文字化输出。代码如下:
test.

  1. function dayinfo(num)
  2. local strdayinfo;
  3. if (num==0) then
  4. strdayinfo="今天";
  5. elseif (num>0) then
  6. strdayinfo=num.."天前";
  7. elseif (num<0) then
  8. strdayinfo=math.abs(num).."天后";
  9. end
  10. print(strdayinfo);
  11. end


delphi主程序

  1. unit Unit1;
  2.  
  3. interface
  4.  
  5. uses
  6. Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  7. Dialogs, StdCtrls,DateUtils;
  8.  
  9. type
  10. TForm1 = class(TForm)
  11. Label1: TLabel;
  12. Button1: TButton;
  13. Edit1: TEdit;
  14. Memo1: TMemo;
  15. procedure FormCreate(Sender: TObject);
  16. procedure Button1Click(Sender: TObject);
  17. private
  18. { Private declarations }
  19. public
  20. { Public declarations }
  21. end;
  22.  
  23. var
  24. Form1: TForm1;
  25.  
  26. implementation
  27.  
  28. {$R *.dfm}
  29. uses
  30. lua, lualib, lauxlib, LuaUtils;
  31.  
  32. procedure TForm1.FormCreate(Sender: TObject);
  33. begin
  34. Edit1.Text:=datetostr(date());
  35. //Edit1.Text:=inttostr(DayOfTheYear(date()));
  36. end;
  37.  
  38. function LuaPrint(L: Plua_State): Integer; cdecl;
  39. var
  40. I, N: Integer;
  41. begin
  42. //LuaShowStack(L, 'fobOp:LuaPrint ?n?');
  43.  
  44. N := lua_gettop(L);
  45. for I := 1 to N do
  46. Form1.Label1.caption:=lua_tostring(L, I);
  47. Result := 0;
  48. end;
  49.  
  50. procedure TForm1.Button1Click(Sender: TObject);
  51. var
  52. L: Plua_State;
  53. begin
  54. // Label1.Caption:= inttostr(DayOfTheYear(date())-DayOfTheYear(strtodate(Edit1.Text)));
  55.  
  56. Memo1.Lines.LoadFromFile('test.lua');
  57. Memo1.Lines.Add('dayinfo('+inttostr(DayOfTheYear(date())-DayOfTheYear(strtodate(Edit1.Text)))+')');
  58. L := lua_open;
  59. try
  60. luaopen_math(L);
  61. LuaRegister(L, 'print', LuaPrint);
  62. LuaLoadBuffer(L, Memo1.Text, 'code');
  63. LuaPCall(L, 0, 0, 0);
  64. finally
  65. lua_close(L);
  66. end;
  67. end;
  68. end.

经测试成功,程序会在label1中根据用户输入的日期来输出是今天,还是n天前或者n天后。

相关文章

Tags : ,
Trackback url : u can trackback from your own site

Leave a Reply