├── .travis.yml ├── CMakeLists.txt ├── LICENSE ├── MANIFEST.in ├── Makefile ├── PKG-INFO ├── README.md ├── setup.cfg ├── setup.py ├── src ├── CMakeLists.txt ├── luainpython.c ├── luainpython.h ├── pythoninlua.c └── pythoninlua.h └── tests ├── test_lua.py └── test_py.lua /.travis.yml: -------------------------------------------------------------------------------- 1 | language: c 2 | 3 | sudo: required 4 | dist: xenial 5 | 6 | compiler: 7 | - gcc 8 | 9 | env: 10 | - LUA_ENV=lua5.1 PY_ENV=python2.7 m_SUFFIX= 11 | - LUA_ENV=lua5.2 PY_ENV=python2.7 m_SUFFIX= 12 | - LUA_ENV=lua5.3 PY_ENV=python2.7 m_SUFFIX= 13 | - LUA_ENV=lua5.1 PY_ENV=python3.6 m_SUFFIX=m 14 | - LUA_ENV=lua5.2 PY_ENV=python3.6 m_SUFFIX=m 15 | - LUA_ENV=lua5.3 PY_ENV=python3.6 m_SUFFIX=m 16 | - LUA_ENV=lua5.1 PY_ENV=python3.8 m_SUFFIX= 17 | - LUA_ENV=lua5.2 PY_ENV=python3.8 m_SUFFIX= 18 | - LUA_ENV=lua5.3 PY_ENV=python3.8 m_SUFFIX= 19 | 20 | 21 | before_install: 22 | - sudo add-apt-repository -y ppa:deadsnakes/ppa 23 | - sudo apt-get update -qq 24 | 25 | install: 26 | - sudo apt-get install -qq --force-yes ${LUA_ENV} 27 | - sudo apt-get install -qq --force-yes ${PY_ENV} 28 | - sudo apt-get install -qq --force-yes lib${LUA_ENV}-dev 29 | - sudo apt-get install -qq --force-yes lib${PY_ENV}-dev 30 | - ${LUA_ENV} -v 31 | - ${PY_ENV} --version 32 | 33 | script: 34 | - cmake -B./build -H. -DPYTHON_INCLUDE_DIR=/usr/include/${PY_ENV}${m_SUFFIX} -DPYTHON_LIBRARY=/usr/lib/x86_64-linux-gnu/lib${PY_ENV}${m_SUFFIX}.so 35 | - cmake --build ./build 36 | - cd ./build/bin 37 | - ${PY_ENV} ../../tests/test_lua.py 38 | - ${LUA_ENV} ../../tests/test_py.lua 39 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12.0) 2 | 3 | set(CMAKE_BUILD_TYPE_INIT "Release") 4 | set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin) 5 | set(LIBRARY_OUTPUT_PATH ${EXECUTABLE_OUTPUT_PATH}) 6 | 7 | project(Lunatic) 8 | 9 | find_package(Lua 5.1 REQUIRED) 10 | find_package(Python REQUIRED COMPONENTS Interpreter Development) 11 | 12 | add_subdirectory(src) 13 | 14 | add_library(python MODULE $) 15 | set_target_properties(python PROPERTIES 16 | PREFIX "") 17 | 18 | add_library(lua MODULE $) 19 | if (WIN32) 20 | set_target_properties(lua PROPERTIES 21 | PREFIX "" 22 | SUFFIX ".pyd") 23 | else (WIN32) 24 | set_target_properties(lua PROPERTIES 25 | PREFIX "") 26 | endif (WIN32) 27 | 28 | target_link_libraries(lua ${LUA_LIBRARIES} ${Python_LIBRARIES}) 29 | target_link_libraries(python ${LUA_LIBRARIES} ${Python_LIBRARIES}) 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | [This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.] 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | 460 | How to Apply These Terms to Your New Libraries 461 | 462 | If you develop a new library, and you want it to be of the greatest 463 | possible use to the public, we recommend making it free software that 464 | everyone can redistribute and change. You can do so by permitting 465 | redistribution under these terms (or, alternatively, under the terms of the 466 | ordinary General Public License). 467 | 468 | To apply these terms, attach the following notices to the library. It is 469 | safest to attach them to the start of each source file to most effectively 470 | convey the exclusion of warranty; and each file should have at least the 471 | "copyright" line and a pointer to where the full notice is found. 472 | 473 | 474 | Copyright (C) 475 | 476 | This library is free software; you can redistribute it and/or 477 | modify it under the terms of the GNU Lesser General Public 478 | License as published by the Free Software Foundation; either 479 | version 2.1 of the License, or (at your option) any later version. 480 | 481 | This library is distributed in the hope that it will be useful, 482 | but WITHOUT ANY WARRANTY; without even the implied warranty of 483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 484 | Lesser General Public License for more details. 485 | 486 | You should have received a copy of the GNU Lesser General Public 487 | License along with this library; if not, write to the Free Software 488 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 489 | 490 | Also add information on how to contact you by electronic and paper mail. 491 | 492 | You should also get your employer (if you work as a programmer) or your 493 | school, if any, to sign a "copyright disclaimer" for the library, if 494 | necessary. Here is a sample; alter the names: 495 | 496 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 497 | library `Frob' (a library for tweaking knobs) written by James Random Hacker. 498 | 499 | , 1 April 1990 500 | Ty Coon, President of Vice 501 | 502 | That's all there is to it! 503 | 504 | 505 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | recursive-include src *.c *.h 2 | include MANIFEST.in python.lua LICENSE Makefile 3 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # 2 | # Simple wrapper for setup.py script 3 | # 4 | 5 | DESTDIR=/ 6 | PYTHON=python 7 | 8 | prefix=/usr 9 | bindir=$(prefix)/bin 10 | 11 | all: 12 | $(PYTHON) setup.py build 13 | 14 | install: 15 | $(PYTHON) setup.py install \ 16 | --root=$(DESTDIR) \ 17 | --prefix=$(prefix) \ 18 | --install-scripts=$(bindir) 19 | 20 | dist: 21 | $(PYTHON) setup.py sdist 22 | 23 | rpm: 24 | $(PYTHON) setup.py bdist_rpm 25 | 26 | -------------------------------------------------------------------------------- /PKG-INFO: -------------------------------------------------------------------------------- 1 | Metadata-Version: 1.0 2 | Name: lunatic-python 3 | Version: 1.0 4 | Summary: Two-way bridge between Python and Lua 5 | Home-page: http://labix.org/lunatic-python 6 | Author: Gustavo Niemeyer 7 | Author-email: gustavo@niemeyer.net 8 | License: LGPL 9 | Description: Lunatic Python is a two-way bridge between Python and Lua, allowing these 10 | languages to intercommunicate. Being two-way means that it allows Lua inside 11 | Python, Python inside Lua, Lua inside Python inside Lua, Python inside Lua 12 | inside Python, and so on. 13 | 14 | Platform: UNKNOWN 15 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Lunatic-Python 2 | 3 | [![Build Status](https://travis-ci.org/bastibe/lunatic-python.svg?branch=master)](https://travis-ci.org/bastibe/lunatic-python) 4 | [![License: LGP-L2.1](https://img.shields.io/badge/license-LGPL%202.1-blue.svg)](https://opensource.org/licenses/LGPL-2.1) 5 | 6 | Details 7 | ======= 8 | 9 | This is a fork of Lunatic Python, which can be found on the 'net at http://labix.org/lunatic-python. 10 | 11 | Sadly, Lunatic Python is very much outdated and won't work with either a current Python or Lua. 12 | 13 | This is an updated version of lunatic-python that works with Python 2.7-3.x and Lua 5.1-5.3. 14 | I tried contacting the original author of Lunatic Python, but got no response. 15 | 16 | Installing 17 | ---------- 18 | 19 | To install, you will need to have the Python and Lua development libraries on your system. If you 20 | do, use the recommended methods (`pip`, `easy-install`, etc) to install lunatic-python. 21 | 22 | This version has been modified to compile under Ubuntu. I haven't tested it under other 23 | distributions, your mileage may vary. 24 | 25 | Introduction 26 | ------------ 27 | 28 | Lunatic Python is a two-way bridge between Python and Lua, allowing these languages to intercommunicate. Being two-way means that it allows Lua inside Python, Python inside Lua, Lua inside Python inside Lua, Python inside Lua inside Python, and so on. 29 | 30 | Why? 31 | 32 | Even though the project was born as an experiment, it's already being used in real world projects to integrate features from both languages. Please, let me know if you use it in real world projects. 33 | 34 | Examples 35 | 36 | Lua inside Python 37 | A basic example. 38 | 39 | ```lua 40 | >>> import lua 41 | >>> lg = lua.globals() 42 | >>> lg.string 43 | 44 | >>> lg.string.lower 45 | 46 | >>> lg.string.lower("Hello world!") 47 | 'hello world!' 48 | ``` 49 | 50 | Now, let's put a local object into Lua space. 51 | 52 | ```lua 53 | >>> d = {} 54 | >>> lg.d = d 55 | >>> lua.execute("d['key'] = 'value'") 56 | >>> d 57 | {'key': 'value'} 58 | Can we get the reference back from Lua space? 59 | >>> d2 = lua.eval("d") 60 | >>> d is d2 61 | True 62 | ``` 63 | 64 | Good! 65 | 66 | Is the python interface available inside the Lua interpreter? 67 | 68 | ```lua 69 | >>> lua.eval("python") 70 | 71 | ``` 72 | 73 | Yes, it looks so. Let's nest some evaluations and see a local reference passing through. 74 | 75 | ```python 76 | >>> class MyClass: pass 77 | ... 78 | >>> obj = MyClass() 79 | >>> obj 80 | <__main__.MyClass instance at 0x403ccb4c> 81 | >>> lua.eval(r"python.eval('lua.eval(\"python.eval(\'obj\')\")')") 82 | <__main__.MyClass instance at 0x403ccb4c> 83 | ``` 84 | 85 | Are you still following me? Good. Then you've probably noticed that the Python interpreter state inside the Lua interpreter state is the same as the outside Python we're running. Let's see that in a more comfortable way. 86 | 87 | ```python 88 | >>> lua.execute("pg = python.globals()") 89 | >>> lua.eval("pg.obj") 90 | <__main__.MyClass instance at 0x403ccb4c> 91 | ``` 92 | 93 | Things get more interesting when we start to really mix Lua and Python code. 94 | 95 | ```python 96 | >>> table = lua.eval("table") 97 | >>> def show(key, value): 98 | ... print "key is %s and value is %s" % (`key`, `value`) 99 | ... 100 | >>> t = lua.eval("{a=1, b=2, c=3}") 101 | >>> table.foreach(t, show) 102 | key is 'a' and value is 1 103 | key is 'c' and value is 3 104 | key is 'b' and value is 2 105 | >>> 106 | ``` 107 | 108 | Of course, in this case the same could be achieved easily with Python. 109 | 110 | ```python 111 | >>> def show(key, value): 112 | ... print "key is %s and value is %s" % (`key`, `value`) 113 | ... 114 | >>> t = lua.eval("{a=1, b=2, c=3}") 115 | >>> for k in t: 116 | ... show(k, t[k]) 117 | ... 118 | key is 'a' and value is 1 119 | key is 'c' and value is 3 120 | key is 'b' and value is 2 121 | ``` 122 | 123 | Python inside Lua 124 | ----------------- 125 | 126 | Now, let's have a look from another perspective. The basic idea is exactly the same. 127 | 128 | ```python 129 | > require("python") 130 | > python.execute("import string") 131 | > pg = python.globals() 132 | > =pg.string 133 | 134 | > =pg.string.lower("Hello world!") 135 | hello world! 136 | ``` 137 | 138 | As Lua is mainly an embedding language, getting access to the batteries included in Python may be interesting. 139 | 140 | ```python 141 | > re = python.import("re") 142 | > pattern = re.compile("^Hel(lo) world!") 143 | > match = pattern.match("Hello world!") 144 | > =match.group(1) 145 | lo 146 | ``` 147 | 148 | Just like in the Python example, let's put a local object in Python space. 149 | 150 | ```python 151 | > d = {} 152 | > pg.d = d 153 | > python.execute("d['key'] = 'value'") 154 | > table.foreach(d, print) 155 | key value 156 | ``` 157 | 158 | Again, let's grab back the reference from Python space. 159 | 160 | ```python 161 | > d2 = python.eval("d") 162 | > print(d == d2) 163 | true 164 | ``` 165 | 166 | Is the Lua interface available to Python? 167 | 168 | ```pythom 169 | > =python.eval("lua") 170 | 171 | ``` 172 | 173 | Good. So let's do the nested trick in Lua as well. 174 | 175 | ```python 176 | > t = {} 177 | > =t 178 | table: 0x80fbdb8 179 | > =python.eval("lua.eval('python.eval(\"lua.eval(\\'t\\')\")')") 180 | table: 0x80fbdb8 181 | > 182 | ``` 183 | 184 | It means that the Lua interpreter state inside the Python interpreter is the same as the outside Lua interpreter state. Let's show that in a more obvious way. 185 | 186 | ```lua 187 | > python.execute("lg = lua.globals()") 188 | > =python.eval("lg.t") 189 | table: 0x80fbdb8 190 | ``` 191 | 192 | Now for the mixing example. 193 | 194 | ```lua 195 | > function notthree(num) 196 | >> return (num ~= 3) 197 | >> end 198 | > l = python.eval("[1, 2, 3, 4, 5]") 199 | > filter = python.eval("filter") 200 | > =filter(notthree, l) 201 | [1, 2, 4, 5] 202 | ``` 203 | 204 | Documentation 205 | ============= 206 | 207 | Theory 208 | ------ 209 | 210 | The bridging mechanism consists of creating the missing interpreter state inside the host interpreter. That is, when you run the bridging system inside Python, a Lua interpreter is created; when you run the system inside Lua, a Python interpreter is created. 211 | Once both interpreter states are available, these interpreters are provided with the necessary tools to interact freely with each other. The given tools offer not only the ability of executing statements inside the alien interpreter, but also to acquire individual objects and interact with them inside the native state. This magic is done by two special object types, which act bridging native object access to the alien interpreter state. 212 | 213 | Almost every object which is passed between Python and Lua is encapsulated in the language specific bridging object type. The only types which are not encapsulated are strings and numbers, which are converted to the native equivalent objects. 214 | Besides that, the Lua side also has special treatment for encapsulated Python functions and methods. The most obvious way to implement calling of Python objects inside the Lua interpreter is to implement a `__call` function in the bridging object metatable. Unfortunately this mechanism is not supported in certain situations, since some places test if the object type is a function, which is not the case of the bridging object. To overwhelm these problems, Python functions and methods are automatically converted to native Lua function closures, becoming accessible in every Lua context. Callable object instances which are not functions nor methods, on the other hand, will still use the metatable mechanism. Luckily, they may also be converted in a native function closure using the `asfunc()` function, if necessary. 215 | 216 | Attribute vs. Subscript object access 217 | ------------------------------------- 218 | 219 | Accessing an attribute or using the subscript operator in Lua give access to the same information. This behavior is reflected in the Python special object that encapsulates Lua objects, allowing Lua tables to be accessed in a more comfortable way, and also giving access to objects which use protected Python keywords (such as the print function). For example: 220 | 221 | ```python 222 | >>> string = lua.eval("string") 223 | >>> string.lower 224 | 225 | >>> string["lower"] 226 | 227 | ``` 228 | 229 | Using Python from the Lua side requires a little bit more attention, since Python has a more strict syntax than Lua. The later makes no distinction between attribute and subscript access, so we need some way to know what kind of access is desired at a given moment. This control is provided using two functions: `asindx()` and `asattr()`. These functions receive a single Python object as parameter, and return the same object with the given access discipline. Notice that dictionaries and lists use the index discipline by default, while other objects use the attribute discipline. For example: 230 | 231 | ```python 232 | > dict = python.eval("{}") 233 | > =dict.keys 234 | nil 235 | > dict.keys = 10 236 | > print(dict["keys"]) 237 | 10 238 | > =dict 239 | {'keys': 10} 240 | > =dict.keys = 10 241 | n.asattr(dict) 242 | > =dict.keys 243 | function: 0x80fa9b8 244 | > =dict.keys() 245 | ['keys'] 246 | ``` 247 | 248 | Lua inside Python 249 | ----------------- 250 | 251 | When executing Python as the host language, the Lua functionality is accessed by importing the lua module. When Lua is the host language, the lua module will already be available in the global Python scope. 252 | Below is a description of the functions available in the lua module. 253 | 254 | ```python 255 | lua.execute(statement) 256 | ``` 257 | 258 | This function will execute the given statement inside the Lua interpreter state. 259 | Examples: 260 | 261 | ```lua 262 | >>> lua.execute("foo = 'bar'") 263 | lua.eval(expression) 264 | ``` 265 | 266 | This function will evaluate the given expression inside the Lua interpreter state, and return the result. It may be used to acquire any object from the Lua interpreter state. 267 | Examples: 268 | 269 | ```lua 270 | >>> lua.eval("'foo'..2") 271 | 'foo2' 272 | >>> lua.eval('string') 273 | 274 | >>> string = lua.eval('string') 275 | >>> string.lower("Hello world!") 276 | 'hello world!' 277 | ``` 278 | 279 | ```lua 280 | lua.globals() 281 | ``` 282 | 283 | Return the Lua global scope from the interpreter state. 284 | 285 | Examples: 286 | 287 | ```lua 288 | >>> lg = lua.globals() 289 | >>> lg.string.lower("Hello world!") 290 | 'hello world!' 291 | >>> lg["string"].lower("Hello world!") 292 | 'hello world!' 293 | >>> lg["print"] 294 | 295 | >>> lg["print"]("Hello world!") 296 | Hello world! 297 | ``` 298 | 299 | ```lua 300 | lua.require(name) 301 | ``` 302 | 303 | Executes the require() Lua function, importing the given module. 304 | 305 | Examples: 306 | ```lua 307 | >>> lua.require("testmod") 308 | True 309 | >>> lua.execute("func()") 310 | I'm func in testmod! 311 | ``` 312 | 313 | Python inside Lua 314 | ----------------- 315 | 316 | Unlike Python, Lua has no default path to its modules. Thus, the default path of the real Lua module of Lunatic Python is together with the Python module, and a python.lua stub is provided. This stub must be placed in a path accessible by the Lua require() mechanism, and once imported it will locate the real module and load it. 317 | 318 | Unfortunately, there's a minor inconvenience for our purposes regarding the Lua system which imports external shared objects. The hardcoded behavior of the loadlib() function is to load shared objects without exporting their symbols. This is usually not a problem in the Lua world, but we're going a little beyond their usual requirements here. We're loading the Python interpreter as a shared object, and the Python interpreter may load its own external modules which are compiled as shared objects as well, and these will want to link back to the symbols in the Python interpreter. Luckily, fixing this problem is easier than explaining the problem. It's just a matter of replacing the flag RTLD_NOW in the loadlib.c file of the Lua distribution by the or'ed version RTLD_NOW|RTLD_GLOBAL. This will avoid "undefined symbol" errors which could eventually happen. 319 | Below is a description of the functions available in the python module. 320 | 321 | ```python 322 | python.execute(statement) 323 | ``` 324 | 325 | This function will execute the given statement inside the Python interpreter state. 326 | Examples: 327 | 328 | ```python 329 | > python.execute("foo = 'bar'") 330 | ``` 331 | 332 | ```python 333 | python.eval(expression) 334 | ``` 335 | 336 | This function will evaluate the given expression inside the Python interpreter state, and return the result. It may be used to acquire any object from the Python interpreter state. 337 | 338 | Examples: 339 | 340 | ```python 341 | > python.execute("import string") 342 | > =python.eval("string") 343 | 344 | > string = python.eval("string") 345 | > =string.lower("Hello world!") 346 | hello world! 347 | ``` 348 | 349 | ```python 350 | python.globals() 351 | ``` 352 | 353 | Return the Python global scope dictionary from the interpreter state. 354 | Examples: 355 | 356 | ```python 357 | > python.execute("import string") 358 | > pg = python.globals() 359 | > =pg.string.lower("Hello world!") 360 | hello world! 361 | > =pg["string"].lower("Hello world!") 362 | hello world! 363 | ``` 364 | 365 | ```python 366 | python.locals() 367 | ``` 368 | 369 | Return the Python local scope dictionary from the interpreter state. 370 | Examples: 371 | 372 | ```python 373 | > function luafunc() 374 | >> print(python.globals().var) 375 | >> print(python.locals().var) 376 | >> end 377 | > python.execute("def func():\n var = 'value'\n lua.execute('luafunc()')") 378 | > python.execute("func()") 379 | nil 380 | value 381 | ``` 382 | 383 | ```python 384 | python.builtins() 385 | ``` 386 | 387 | Return the Python builtins module dictionary from the interpreter state. 388 | Examples: 389 | 390 | ```python 391 | > pb = python.builtins() 392 | > =pb.len("Hello world!") 393 | 12 394 | ``` 395 | 396 | ```python 397 | python.import(name) 398 | ``` 399 | 400 | Imports and returns the given Python module. 401 | Examples: 402 | 403 | ```python 404 | > os = python.import("os") 405 | > =os.getcwd() 406 | /home/niemeyer/src/lunatic-python 407 | ``` 408 | 409 | ```python 410 | python.asattr(pyobj) 411 | ``` 412 | 413 | Return a copy of the given Python object with an attribute access discipline. 414 | Examples: 415 | 416 | ```python 417 | > dict = python.eval("{}") 418 | > =dict.keys 419 | nil 420 | > dict.keys = 10 421 | > print(dict["keys"]) 422 | 10 423 | > =dict 424 | {'keys': 10} 425 | > =dict.keys = 10 426 | n.asattr(dict) 427 | > =dict.keys 428 | function: 0x80fa9b8 429 | > =dict.keys() 430 | ['keys'] 431 | ``` 432 | 433 | ```python 434 | python.asindx(pyobj) 435 | ``` 436 | 437 | Return a copy of the given Python object with an index access discipline. 438 | Examples: 439 | 440 | ```python 441 | > buffer = python.eval("buffer('foobar')") 442 | > =buffer[0] 443 | stdin:1: unknown attribute in python object 444 | stack traceback: 445 | [C]: ? 446 | stdin:1: in main chunk 447 | [C]: ? 448 | > buffer = python.asindx(buffer) 449 | > =buffer[0] 450 | f 451 | ``` 452 | 453 | ```python 454 | python.asfunc(pyobj) 455 | ``` 456 | 457 | Return a copy of the given Python object enclosed in a Lua function closure. This is useful to use Python callable instances in places that require a Lua function. Python methods and functions are automatically converted to Lua functions, and don't require to be explicitly converted. 458 | Examples: 459 | 460 | ```python 461 | > python.execute("class Join:\n def __call__(self, *args):\n return '-'.join(args)") 462 | > join = python.eval("Join()") 463 | > =join 464 | <__main__.Join instance at 0x403a864c> 465 | > =join('foo', 'bar') 466 | foo-bar 467 | > =table.foreach({foo='bar'}, join) 468 | stdin:1: bad argument #2 to `foreach' (function expected, got userdata) 469 | stack traceback: 470 | [C]: in function `foreach' 471 | stdin:1: in main chunk 472 | [C]: ? 473 | > =table.foreach({foo='bar'}, python.asfunc(join)) 474 | foo-bar 475 | ``` 476 | 477 | License 478 | ------- 479 | 480 | Lunatic Python is available under the LGPL license. 481 | 482 | Download 483 | -------- 484 | Available files: 485 | • lunatic-python-1.0.tar.bz2 486 | Author 487 | Gustavo Niemeyer 488 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_rpm] 2 | doc_files = python.lua LICENSE 3 | use_bzip2 = 1 4 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import sys 4 | import os 5 | 6 | if sys.version > '3': 7 | PY3 = True 8 | else: 9 | PY3 = False 10 | 11 | if PY3: 12 | import subprocess as commands 13 | else: 14 | import commands 15 | from distutils.core import setup, Extension 16 | from distutils.sysconfig import get_python_lib, get_python_version 17 | 18 | if os.path.isfile("MANIFEST"): 19 | os.unlink("MANIFEST") 20 | 21 | presult, poutput = commands.getstatusoutput("pkg-config --exists lua5.2") 22 | HAS_LUA5_2 = (presult == 0) 23 | 24 | # You may have to change these 25 | if HAS_LUA5_2: 26 | LUAVERSION = "5.2" 27 | else: 28 | LUAVERSION = "5.1" 29 | 30 | PYTHONVERSION = get_python_version() 31 | PYLIBS = ["python" + get_python_version(), "pthread", "util"] 32 | PYLIBDIR = [get_python_lib(standard_lib=True) + "/config"] 33 | LUALIBS = ["lua" + LUAVERSION] 34 | LUALIBDIR = [] 35 | 36 | def pkgconfig(*packages): 37 | # map pkg-config output to kwargs for distutils.core.Extension 38 | flag_map = {'-I': 'include_dirs', '-L': 'library_dirs', '-l': 'libraries'} 39 | 40 | combined_pcoutput = '' 41 | for package in packages: 42 | (pcstatus, pcoutput) = commands.getstatusoutput( 43 | "pkg-config --libs --cflags %s" % package) 44 | if pcstatus == 0: 45 | combined_pcoutput += ' ' + pcoutput 46 | else: 47 | sys.exit("pkg-config failed for %s; " 48 | "most recent output was:\n%s" % 49 | (", ".join(packages), pcoutput)) 50 | 51 | kwargs = {} 52 | for token in combined_pcoutput.split(): 53 | if token[:2] in flag_map: 54 | kwargs.setdefault(flag_map.get(token[:2]), []).append(token[2:]) 55 | else: # throw others to extra_link_args 56 | kwargs.setdefault('extra_link_args', []).append(token) 57 | 58 | if PY3: 59 | items = kwargs.items() 60 | else: 61 | items = kwargs.iteritems() 62 | for k, v in items: # remove duplicated 63 | kwargs[k] = list(set(v)) 64 | 65 | return kwargs 66 | 67 | lua_pkgconfig = pkgconfig('lua' + LUAVERSION, 'python-' + PYTHONVERSION) 68 | lua_pkgconfig['extra_compile_args'] = ['-I/usr/include/lua'+LUAVERSION] 69 | 70 | setup(name="lunatic-python", 71 | version="1.0", 72 | description="Two-way bridge between Python and Lua", 73 | author="Gustavo Niemeyer", 74 | author_email="gustavo@niemeyer.net", 75 | url="http://labix.org/lunatic-python", 76 | license="LGPL", 77 | long_description="""\ 78 | Lunatic Python is a two-way bridge between Python and Lua, allowing these 79 | languages to intercommunicate. Being two-way means that it allows Lua inside 80 | Python, Python inside Lua, Lua inside Python inside Lua, Python inside Lua 81 | inside Python, and so on. 82 | """, 83 | ext_modules=[ 84 | Extension("lua-python", 85 | ["src/pythoninlua.c", "src/luainpython.c"], 86 | **lua_pkgconfig), 87 | Extension("lua", 88 | ["src/pythoninlua.c", "src/luainpython.c"], 89 | **lua_pkgconfig), 90 | ], 91 | ) 92 | -------------------------------------------------------------------------------- /src/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | add_library(src OBJECT luainpython.c pythoninlua.c) 2 | set_target_properties(src PROPERTIES 3 | POSITION_INDEPENDENT_CODE TRUE) 4 | 5 | target_include_directories(src PRIVATE ${LUA_INCLUDE_DIR} ${Python_INCLUDE_DIRS}) 6 | 7 | target_compile_definitions(src PRIVATE LUA_LIB) 8 | if (WIN32) 9 | target_compile_definitions(src PRIVATE LUA_BUILD_AS_DLL) 10 | endif (WIN32) 11 | 12 | if (UNIX) 13 | get_filename_component(PYTHON_LIBRT ${Python_LIBRARIES} NAME) 14 | target_compile_definitions(src PRIVATE PYTHON_LIBRT=${PYTHON_LIBRT}) 15 | endif (UNIX) 16 | 17 | if (CMAKE_COMPILER_IS_GNUCC) 18 | target_compile_options(src PUBLIC -Wall -pedantic -std=c99) 19 | endif (CMAKE_COMPILER_IS_GNUCC) 20 | -------------------------------------------------------------------------------- /src/luainpython.c: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Lunatic Python 4 | -------------- 5 | 6 | Copyright (c) 2002-2005 Gustavo Niemeyer 7 | 8 | This library is free software; you can redistribute it and/or 9 | modify it under the terms of the GNU Lesser General Public 10 | License as published by the Free Software Foundation; either 11 | version 2.1 of the License, or (at your option) any later version. 12 | 13 | This library is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 16 | Lesser General Public License for more details. 17 | 18 | You should have received a copy of the GNU Lesser General Public 19 | License along with this library; if not, write to the Free Software 20 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 21 | 22 | */ 23 | #define PY_SSIZE_T_CLEAN 24 | #include 25 | 26 | /* need this to build with Lua 5.2: enables lua_strlen() macro */ 27 | #define LUA_COMPAT_ALL 28 | 29 | #include 30 | #include 31 | #include 32 | #include 33 | 34 | #include "pythoninlua.h" 35 | #include "luainpython.h" 36 | 37 | lua_State *LuaState = NULL; 38 | 39 | static PyObject *LuaObject_New(lua_State *L, int n) 40 | { 41 | LuaObject *obj = PyObject_New(LuaObject, &LuaObject_Type); 42 | if (obj) 43 | { 44 | lua_pushvalue(L, n); 45 | obj->ref = luaL_ref(L, LUA_REGISTRYINDEX); 46 | obj->refiter = 0; 47 | } 48 | return (PyObject*) obj; 49 | } 50 | 51 | PyObject *LuaConvert(lua_State *L, int n) 52 | { 53 | 54 | PyObject *ret = NULL; 55 | 56 | switch (lua_type(L, n)) { 57 | 58 | case LUA_TNIL: 59 | Py_INCREF(Py_None); 60 | ret = Py_None; 61 | break; 62 | 63 | case LUA_TSTRING: { 64 | size_t len; 65 | const char *s = lua_tolstring(L, n, &len); 66 | ret = PyUnicode_FromStringAndSize(s, len); 67 | if (!ret) 68 | { 69 | PyErr_Clear(); 70 | ret = PyBytes_FromStringAndSize(s, len); 71 | } 72 | break; 73 | } 74 | 75 | case LUA_TNUMBER: { 76 | lua_Number num = lua_tonumber(L, n); 77 | if (num != (long)num) { 78 | ret = PyFloat_FromDouble(num); 79 | } else { 80 | ret = PyLong_FromLong((long)num); 81 | } 82 | break; 83 | } 84 | 85 | case LUA_TBOOLEAN: 86 | ret = lua_toboolean(L, n) ? Py_True : Py_False; 87 | Py_INCREF(ret); 88 | break; 89 | 90 | case LUA_TUSERDATA: { 91 | py_object *obj = luaPy_to_pobject(L, n); 92 | 93 | if (obj) { 94 | Py_INCREF(obj->o); 95 | ret = obj->o; 96 | break; 97 | } 98 | 99 | /* Otherwise go on and handle as custom. */ 100 | } 101 | 102 | default: 103 | ret = LuaObject_New(L, n); 104 | break; 105 | } 106 | 107 | return ret; 108 | } 109 | 110 | static PyObject *LuaCall(lua_State *L, PyObject *args) 111 | { 112 | PyObject *ret = NULL; 113 | PyObject *arg; 114 | #ifdef PY_SSIZE_T_CLEAN 115 | Py_ssize_t nargs, i; 116 | #else 117 | int nargs, i; 118 | #endif 119 | int rc; 120 | 121 | if (!PyTuple_Check(args)) { 122 | PyErr_SetString(PyExc_TypeError, "tuple expected"); 123 | lua_settop(L, 0); 124 | return NULL; 125 | } 126 | 127 | nargs = PyTuple_Size(args); 128 | for (i = 0; i != nargs; i++) { 129 | arg = PyTuple_GetItem(args, i); 130 | if (arg == NULL) { 131 | PyErr_Format(PyExc_TypeError, 132 | "failed to get tuple item #%d", i); 133 | lua_settop(L, 0); 134 | return NULL; 135 | } 136 | rc = py_convert(L, arg); 137 | if (!rc) { 138 | PyErr_Format(PyExc_TypeError, 139 | "failed to convert argument #%d", i); 140 | lua_settop(L, 0); 141 | return NULL; 142 | } 143 | } 144 | 145 | if (lua_pcall(L, nargs, LUA_MULTRET, 0) != 0) { 146 | PyErr_Format(PyExc_Exception, 147 | "error: %s", lua_tostring(L, -1)); 148 | return NULL; 149 | } 150 | 151 | nargs = lua_gettop(L); 152 | if (nargs == 1) { 153 | ret = LuaConvert(L, 1); 154 | if (!ret) { 155 | PyErr_SetString(PyExc_TypeError, 156 | "failed to convert return"); 157 | lua_settop(L, 0); 158 | Py_DECREF(ret); 159 | return NULL; 160 | } 161 | } else if (nargs > 1) { 162 | ret = PyTuple_New(nargs); 163 | if (!ret) { 164 | PyErr_SetString(PyExc_RuntimeError, 165 | "failed to create return tuple"); 166 | lua_settop(L, 0); 167 | return NULL; 168 | } 169 | for (i = 0; i != nargs; i++) { 170 | arg = LuaConvert(L, i+1); 171 | if (!arg) { 172 | PyErr_Format(PyExc_TypeError, 173 | "failed to convert return #%d", i); 174 | lua_settop(L, 0); 175 | Py_DECREF(ret); 176 | return NULL; 177 | } 178 | PyTuple_SetItem(ret, i, arg); 179 | } 180 | } else { 181 | Py_INCREF(Py_None); 182 | ret = Py_None; 183 | } 184 | 185 | lua_settop(L, 0); 186 | 187 | return ret; 188 | } 189 | 190 | static void LuaObject_dealloc(LuaObject *self) 191 | { 192 | luaL_unref(LuaState, LUA_REGISTRYINDEX, self->ref); 193 | if (self->refiter) 194 | luaL_unref(LuaState, LUA_REGISTRYINDEX, self->refiter); 195 | Py_TYPE(self)->tp_free((PyObject *)self); 196 | } 197 | 198 | static PyObject *LuaObject_getattr(PyObject *obj, PyObject *attr) 199 | { 200 | lua_rawgeti(LuaState, LUA_REGISTRYINDEX, ((LuaObject*)obj)->ref); 201 | if (lua_isnil(LuaState, -1)) { 202 | lua_pop(LuaState, 1); 203 | PyErr_SetString(PyExc_RuntimeError, "lost reference"); 204 | return NULL; 205 | } 206 | 207 | if (!lua_isstring(LuaState, -1) 208 | && !lua_istable(LuaState, -1) 209 | && !lua_isuserdata(LuaState, -1)) 210 | { 211 | lua_pop(LuaState, 1); 212 | PyErr_SetString(PyExc_RuntimeError, "not an indexable value"); 213 | return NULL; 214 | } 215 | 216 | PyObject *ret = NULL; 217 | int rc = py_convert(LuaState, attr); 218 | if (rc) { 219 | lua_gettable(LuaState, -2); 220 | ret = LuaConvert(LuaState, -1); 221 | } else { 222 | PyErr_SetString(PyExc_ValueError, "can't convert attr/key"); 223 | } 224 | lua_settop(LuaState, 0); 225 | return ret; 226 | } 227 | 228 | static int LuaObject_setattr(PyObject *obj, PyObject *attr, PyObject *value) 229 | { 230 | int ret = -1; 231 | int rc; 232 | lua_rawgeti(LuaState, LUA_REGISTRYINDEX, ((LuaObject*)obj)->ref); 233 | if (lua_isnil(LuaState, -1)) { 234 | lua_pop(LuaState, 1); 235 | PyErr_SetString(PyExc_RuntimeError, "lost reference"); 236 | return -1; 237 | } 238 | if (!lua_istable(LuaState, -1)) { 239 | lua_pop(LuaState, -1); 240 | PyErr_SetString(PyExc_TypeError, "Lua object is not a table"); 241 | return -1; 242 | } 243 | rc = py_convert(LuaState, attr); 244 | if (rc) { 245 | if (NULL == value) { 246 | lua_pushnil(LuaState); 247 | rc = 1; 248 | } else { 249 | rc = py_convert(LuaState, value); 250 | } 251 | 252 | if (rc) { 253 | lua_settable(LuaState, -3); 254 | ret = 0; 255 | } else { 256 | PyErr_SetString(PyExc_ValueError, 257 | "can't convert value"); 258 | } 259 | } else { 260 | PyErr_SetString(PyExc_ValueError, "can't convert key/attr"); 261 | } 262 | lua_settop(LuaState, 0); 263 | return ret; 264 | } 265 | 266 | static PyObject *LuaObject_str(PyObject *obj) 267 | { 268 | PyObject *ret = NULL; 269 | const char *s; 270 | lua_rawgeti(LuaState, LUA_REGISTRYINDEX, ((LuaObject*)obj)->ref); 271 | if (luaL_callmeta(LuaState, -1, "__tostring")) { 272 | s = lua_tostring(LuaState, -1); 273 | lua_pop(LuaState, 1); 274 | if (s) ret = PyUnicode_FromString(s); 275 | } 276 | if (!ret) { 277 | int type = lua_type(LuaState, -1); 278 | switch (type) { 279 | case LUA_TTABLE: 280 | case LUA_TFUNCTION: 281 | ret = PyUnicode_FromFormat("", 282 | lua_typename(LuaState, type), 283 | lua_topointer(LuaState, -1)); 284 | break; 285 | 286 | case LUA_TUSERDATA: 287 | case LUA_TLIGHTUSERDATA: 288 | ret = PyUnicode_FromFormat("", 289 | lua_typename(LuaState, type), 290 | lua_touserdata(LuaState, -1)); 291 | break; 292 | 293 | case LUA_TTHREAD: 294 | ret = PyUnicode_FromFormat("", 295 | lua_typename(LuaState, type), 296 | (void*)lua_tothread(LuaState, -1)); 297 | break; 298 | 299 | default: 300 | ret = PyUnicode_FromFormat("", 301 | lua_typename(LuaState, type)); 302 | break; 303 | 304 | } 305 | } 306 | lua_pop(LuaState, 1); 307 | return ret; 308 | } 309 | 310 | #if LUA_VERSION_NUM == 501 311 | #ifdef LUA_OK // defined in LuaJIT 312 | #undef LUA_OK 313 | #endif 314 | enum 315 | { 316 | LUA_OK, LUA_OPEQ, LUA_OPLT, LUA_OPLE, 317 | }; 318 | static int lua_compare(lua_State *L, int lhs, int rhs, int op) 319 | { 320 | switch(op) 321 | { 322 | case LUA_OPEQ: 323 | return lua_equal(L, lhs, rhs); 324 | case LUA_OPLT: 325 | return lua_lessthan(L, lhs, rhs); 326 | case LUA_OPLE: 327 | return lua_lessthan(L, lhs, rhs) || lua_equal(L, lhs, rhs); 328 | } 329 | return 0; 330 | } 331 | #endif 332 | static int LuaObject_pcmp(lua_State *L) 333 | { 334 | int op = lua_tointeger(L, -3); 335 | switch(op) 336 | { 337 | case Py_EQ: 338 | lua_pushboolean(L, lua_compare(L, -2, -1, LUA_OPEQ)); 339 | break; 340 | case Py_NE: 341 | lua_pushboolean(L, !lua_compare(L, -2, -1, LUA_OPEQ)); 342 | break; 343 | case Py_GT: 344 | lua_insert(LuaState, -2); 345 | case Py_LT: 346 | lua_pushboolean(L, lua_compare(L, -2, -1, LUA_OPLT)); 347 | break; 348 | case Py_GE: 349 | lua_insert(LuaState, -2); 350 | case Py_LE: 351 | lua_pushboolean(L, lua_compare(L, -2, -1, LUA_OPLE)); 352 | } 353 | 354 | return 1; 355 | } 356 | 357 | static PyObject* LuaObject_richcmp(PyObject *lhs, PyObject *rhs, int op) 358 | { 359 | if (!LuaObject_Check(rhs)) return Py_False; 360 | 361 | lua_pushcfunction(LuaState, LuaObject_pcmp); 362 | lua_pushinteger(LuaState, op); 363 | lua_rawgeti(LuaState, LUA_REGISTRYINDEX, ((LuaObject *)lhs)->ref); 364 | lua_rawgeti(LuaState, LUA_REGISTRYINDEX, ((LuaObject *)rhs)->ref); 365 | if (lua_pcall(LuaState, 3, 1, 0) != LUA_OK) 366 | { 367 | PyErr_SetString(PyExc_RuntimeError, lua_tostring(LuaState, -1)); 368 | return NULL; 369 | } 370 | return LuaConvert(LuaState, -1); 371 | } 372 | 373 | static PyObject *LuaObject_call(PyObject *obj, PyObject *args) 374 | { 375 | lua_settop(LuaState, 0); 376 | lua_rawgeti(LuaState, LUA_REGISTRYINDEX, ((LuaObject*)obj)->ref); 377 | return LuaCall(LuaState, args); 378 | } 379 | 380 | static PyObject *LuaObject_iternext(LuaObject *obj) 381 | { 382 | PyObject *ret = NULL; 383 | 384 | lua_rawgeti(LuaState, LUA_REGISTRYINDEX, ((LuaObject*)obj)->ref); 385 | 386 | if (obj->refiter == 0) 387 | lua_pushnil(LuaState); 388 | else 389 | lua_rawgeti(LuaState, LUA_REGISTRYINDEX, obj->refiter); 390 | 391 | if (lua_next(LuaState, -2) != 0) { 392 | /* Remove value. */ 393 | lua_pop(LuaState, 1); 394 | ret = LuaConvert(LuaState, -1); 395 | /* Save key for next iteration. */ 396 | if (!obj->refiter) 397 | obj->refiter = luaL_ref(LuaState, LUA_REGISTRYINDEX); 398 | else 399 | lua_rawseti(LuaState, LUA_REGISTRYINDEX, obj->refiter); 400 | } else if (obj->refiter) { 401 | luaL_unref(LuaState, LUA_REGISTRYINDEX, obj->refiter); 402 | obj->refiter = 0; 403 | } 404 | 405 | return ret; 406 | } 407 | 408 | #ifdef PY_SSIZE_T_CLEAN 409 | static Py_ssize_t LuaObject_length(LuaObject *obj) 410 | #else 411 | static int LuaObject_length(LuaObject *obj) 412 | #endif 413 | { 414 | #ifdef PY_SSIZE_T_CLEAN 415 | Py_ssize_t len; 416 | #else 417 | int len; 418 | #endif 419 | lua_rawgeti(LuaState, LUA_REGISTRYINDEX, ((LuaObject*)obj)->ref); 420 | len = luaL_len(LuaState, -1); 421 | lua_settop(LuaState, 0); 422 | return len; 423 | } 424 | 425 | static PyObject *LuaObject_subscript(PyObject *obj, PyObject *key) 426 | { 427 | return LuaObject_getattr(obj, key); 428 | } 429 | 430 | static int LuaObject_ass_subscript(PyObject *obj, 431 | PyObject *key, PyObject *value) 432 | { 433 | return LuaObject_setattr(obj, key, value); 434 | } 435 | 436 | static PyMappingMethods LuaObject_as_mapping = { 437 | #if PY_VERSION_HEX >= 0x02050000 438 | (lenfunc)LuaObject_length, /*mp_length*/ 439 | #else 440 | (inquiry)LuaObject_length, /*mp_length*/ 441 | #endif 442 | (binaryfunc)LuaObject_subscript,/*mp_subscript*/ 443 | (objobjargproc)LuaObject_ass_subscript,/*mp_ass_subscript*/ 444 | }; 445 | 446 | PyTypeObject LuaObject_Type = { 447 | PyVarObject_HEAD_INIT(NULL, 0) 448 | .tp_name = "lua.custom", 449 | .tp_basicsize = sizeof(LuaObject), 450 | .tp_dealloc = (destructor)LuaObject_dealloc, 451 | .tp_repr = LuaObject_str, 452 | .tp_as_mapping = &LuaObject_as_mapping, 453 | .tp_call = (ternaryfunc)LuaObject_call, 454 | .tp_str = LuaObject_str, 455 | .tp_getattro = LuaObject_getattr, 456 | .tp_setattro = LuaObject_setattr, 457 | .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, 458 | .tp_doc = "custom lua object", 459 | .tp_richcompare = LuaObject_richcmp, 460 | .tp_iter = PyObject_SelfIter, 461 | .tp_iternext = (iternextfunc)LuaObject_iternext, 462 | .tp_alloc = PyType_GenericAlloc, 463 | .tp_new = PyType_GenericNew, 464 | .tp_free = PyObject_Del, 465 | }; 466 | 467 | PyObject *Lua_run(PyObject *args, int eval) 468 | { 469 | PyObject *ret; 470 | char *buf = NULL; 471 | char *s; 472 | #ifdef PY_SSIZE_T_CLEAN 473 | Py_ssize_t len; 474 | #else 475 | int len; 476 | #endif 477 | 478 | if (!PyArg_ParseTuple(args, "s#", &s, &len)) 479 | return NULL; 480 | 481 | if (eval) { 482 | buf = (char *) malloc(strlen("return ")+len+1); 483 | strcpy(buf, "return "); 484 | strncat(buf, s, len); 485 | s = buf; 486 | len = strlen("return ")+len; 487 | } 488 | 489 | if (luaL_loadbuffer(LuaState, s, len, "") != 0) { 490 | PyErr_Format(PyExc_RuntimeError, 491 | "error loading code: %s", 492 | lua_tostring(LuaState, -1)); 493 | free(buf); 494 | return NULL; 495 | } 496 | 497 | free(buf); 498 | 499 | if (lua_pcall(LuaState, 0, 1, 0) != 0) { 500 | PyErr_Format(PyExc_RuntimeError, 501 | "error executing code: %s", 502 | lua_tostring(LuaState, -1)); 503 | return NULL; 504 | } 505 | 506 | ret = LuaConvert(LuaState, -1); 507 | lua_settop(LuaState, 0); 508 | return ret; 509 | } 510 | 511 | PyObject *Lua_execute(PyObject *self, PyObject *args) 512 | { 513 | return Lua_run(args, 0); 514 | } 515 | 516 | PyObject *Lua_eval(PyObject *self, PyObject *args) 517 | { 518 | return Lua_run(args, 1); 519 | } 520 | 521 | PyObject *Lua_globals(PyObject *self, PyObject *args) 522 | { 523 | PyObject *ret = NULL; 524 | lua_getglobal(LuaState, "_G"); 525 | if (lua_isnil(LuaState, -1)) { 526 | PyErr_SetString(PyExc_RuntimeError, 527 | "lost globals reference"); 528 | lua_pop(LuaState, 1); 529 | return NULL; 530 | } 531 | ret = LuaConvert(LuaState, -1); 532 | if (!ret) 533 | PyErr_Format(PyExc_TypeError, 534 | "failed to convert globals table"); 535 | lua_settop(LuaState, 0); 536 | return ret; 537 | } 538 | 539 | static PyObject *Lua_require(PyObject *self, PyObject *args) 540 | { 541 | lua_getglobal(LuaState, "require"); 542 | if (lua_isnil(LuaState, -1)) { 543 | lua_pop(LuaState, 1); 544 | PyErr_SetString(PyExc_RuntimeError, "require is not defined"); 545 | return NULL; 546 | } 547 | return LuaCall(LuaState, args); 548 | } 549 | 550 | static PyMethodDef lua_methods[] = 551 | { 552 | {"execute", Lua_execute, METH_VARARGS, NULL}, 553 | {"eval", Lua_eval, METH_VARARGS, NULL}, 554 | {"globals", Lua_globals, METH_NOARGS, NULL}, 555 | {"require", Lua_require, METH_VARARGS, NULL}, 556 | {NULL, NULL} 557 | }; 558 | 559 | #if PY_MAJOR_VERSION >= 3 560 | static struct PyModuleDef lua_module = 561 | { 562 | PyModuleDef_HEAD_INIT, 563 | "lua", 564 | "Lunatic-Python Python-Lua bridge", 565 | -1, 566 | lua_methods 567 | }; 568 | #endif 569 | 570 | PyMODINIT_FUNC PyInit_lua(void) 571 | { 572 | PyObject *m; 573 | if (PyType_Ready(&LuaObject_Type) < 0 || 574 | #if PY_MAJOR_VERSION >= 3 575 | (m = PyModule_Create(&lua_module)) == NULL) 576 | return NULL; 577 | #else 578 | (m = Py_InitModule3("lua", lua_methods, 579 | "Lunatic-Python Python-Lua bridge")) == NULL) 580 | return; 581 | #endif 582 | 583 | if (!LuaState) 584 | { 585 | LuaState = luaL_newstate(); 586 | luaL_openlibs(LuaState); 587 | luaopen_python(LuaState); 588 | lua_settop(LuaState, 0); 589 | } 590 | 591 | #if PY_MAJOR_VERSION >= 3 592 | return m; 593 | #endif 594 | } 595 | -------------------------------------------------------------------------------- /src/luainpython.h: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Lunatic Python 4 | -------------- 5 | 6 | Copyright (c) 2002-2005 Gustavo Niemeyer 7 | 8 | This library is free software; you can redistribute it and/or 9 | modify it under the terms of the GNU Lesser General Public 10 | License as published by the Free Software Foundation; either 11 | version 2.1 of the License, or (at your option) any later version. 12 | 13 | This library is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 16 | Lesser General Public License for more details. 17 | 18 | You should have received a copy of the GNU Lesser General Public 19 | License along with this library; if not, write to the Free Software 20 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 21 | 22 | */ 23 | #ifndef LUAINPYTHON_H 24 | #define LUAINPYTHON_H 25 | 26 | #if LUA_VERSION_NUM == 501 27 | #define luaL_len lua_objlen 28 | #define luaL_setfuncs(L, l, nup) luaL_register(L, NULL, (l)) 29 | #ifdef luaL_newlib // defined in LuaJIT 30 | #undef luaL_newlib 31 | #endif 32 | #define luaL_newlib(L, l) (lua_newtable(L), luaL_register(L, NULL, (l))) 33 | #endif 34 | 35 | typedef struct 36 | { 37 | PyObject_HEAD 38 | int ref; 39 | int refiter; 40 | } LuaObject; 41 | 42 | extern PyTypeObject LuaObject_Type; 43 | 44 | #define LuaObject_Check(op) PyObject_TypeCheck(op, &LuaObject_Type) 45 | 46 | PyObject* LuaConvert(lua_State *L, int n); 47 | 48 | extern lua_State *LuaState; 49 | 50 | #if PY_MAJOR_VERSION < 3 51 | # define PyInit_lua initlua 52 | #endif 53 | PyMODINIT_FUNC PyInit_lua(void); 54 | 55 | #endif 56 | -------------------------------------------------------------------------------- /src/pythoninlua.c: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Lunatic Python 4 | -------------- 5 | 6 | Copyright (c) 2002-2005 Gustavo Niemeyer 7 | 8 | This library is free software; you can redistribute it and/or 9 | modify it under the terms of the GNU Lesser General Public 10 | License as published by the Free Software Foundation; either 11 | version 2.1 of the License, or (at your option) any later version. 12 | 13 | This library is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 16 | Lesser General Public License for more details. 17 | 18 | You should have received a copy of the GNU Lesser General Public 19 | License along with this library; if not, write to the Free Software 20 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 21 | 22 | */ 23 | 24 | #include 25 | #if defined(__linux__) 26 | # include 27 | #endif 28 | 29 | /* need this to build with Lua 5.2: defines luaL_register() macro */ 30 | #define LUA_COMPAT_MODULE 31 | 32 | #include 33 | #include 34 | 35 | #include "pythoninlua.h" 36 | #include "luainpython.h" 37 | 38 | static int py_asfunc_call(lua_State *); 39 | static int py_eval(lua_State *); 40 | 41 | static int py_convert_custom(lua_State *L, PyObject *o, int asindx) 42 | { 43 | py_object *obj = (py_object*) lua_newuserdata(L, sizeof(py_object)); 44 | if (!obj) 45 | luaL_error(L, "failed to allocate userdata object"); 46 | 47 | Py_INCREF(o); 48 | obj->o = o; 49 | obj->asindx = asindx; 50 | luaL_getmetatable(L, POBJECT); 51 | lua_setmetatable(L, -2); 52 | 53 | return 1; 54 | } 55 | 56 | int py_convert(lua_State *L, PyObject *o) 57 | { 58 | int ret = 0; 59 | if (o == Py_None) 60 | { 61 | /* Not really needed, but this way we may check 62 | * for errors with ret == 0. */ 63 | lua_pushnil(L); 64 | ret = 1; 65 | } else if (o == Py_True) { 66 | lua_pushboolean(L, 1); 67 | ret = 1; 68 | } else if (o == Py_False) { 69 | lua_pushboolean(L, 0); 70 | ret = 1; 71 | } else if (PyUnicode_Check(o) || PyBytes_Check(o)) { 72 | PyObject *bstr = PyUnicode_AsEncodedString(o, "utf-8", NULL); 73 | Py_ssize_t len; 74 | char *s; 75 | 76 | PyErr_Clear(); 77 | PyBytes_AsStringAndSize(bstr ? bstr : o, &s, &len); 78 | lua_pushlstring(L, s, len); 79 | if (bstr) Py_DECREF(bstr); 80 | ret = 1; 81 | #if PY_MAJOR_VERSION < 3 82 | } else if (PyInt_Check(o)) { 83 | lua_pushnumber(L, (lua_Number)PyInt_AsLong(o)); 84 | ret = 1; 85 | #endif 86 | } else if (PyLong_Check(o)) { 87 | lua_pushnumber(L, (lua_Number)PyLong_AsLong(o)); 88 | ret = 1; 89 | } else if (PyFloat_Check(o)) { 90 | lua_pushnumber(L, (lua_Number)PyFloat_AsDouble(o)); 91 | ret = 1; 92 | } else if (LuaObject_Check(o)) { 93 | lua_rawgeti(L, LUA_REGISTRYINDEX, ((LuaObject*)o)->ref); 94 | ret = 1; 95 | } else { 96 | int asindx = PyDict_Check(o) || PyList_Check(o) || PyTuple_Check(o); 97 | ret = py_convert_custom(L, o, asindx); 98 | } 99 | return ret; 100 | } 101 | 102 | static int py_object_call(lua_State *L) 103 | { 104 | PyObject *args; 105 | PyObject *value; 106 | PyObject *pKywdArgs = NULL; 107 | int nargs = lua_gettop(L)-1; 108 | int ret = 0; 109 | int i; 110 | py_object *obj = (py_object*) luaL_checkudata(L, 1, POBJECT); 111 | assert(obj); 112 | 113 | if (!PyCallable_Check(obj->o)) 114 | return luaL_error(L, "object is not callable"); 115 | 116 | // passing a single table forces named keyword call style, e.g. plt.plot{x, y, c='red'} 117 | if (nargs==1 && lua_istable(L, 2)) { 118 | lua_pushnil(L); /* first key */ 119 | nargs=0; 120 | while (lua_next(L, 2) != 0) { 121 | if (lua_isnumber(L, -2)) { 122 | int i = lua_tointeger(L, -2); 123 | nargs = i < nargs ? nargs : i; 124 | } 125 | lua_pop(L, 1); 126 | } 127 | args = PyTuple_New(nargs); 128 | if (!args) { 129 | PyErr_Print(); 130 | return luaL_error(L, "failed to create arguments tuple"); 131 | } 132 | pKywdArgs = PyDict_New(); 133 | if (!pKywdArgs) { 134 | Py_DECREF(args); 135 | PyErr_Print(); 136 | return luaL_error(L, "failed to create arguments dictionary"); 137 | } 138 | lua_pushnil(L); /* first key */ 139 | while (lua_next(L, 2) != 0) { 140 | if (lua_isnumber(L, -2)) { 141 | PyObject *arg = LuaConvert(L, -1); 142 | if (!arg) { 143 | Py_DECREF(args); 144 | Py_DECREF(pKywdArgs); 145 | return luaL_error(L, "failed to convert argument #%d", lua_tointeger(L, -2)); 146 | } 147 | PyTuple_SetItem(args, lua_tointeger(L, -2)-1, arg); 148 | } 149 | else if (lua_isstring(L, -2)) { 150 | PyObject *arg = LuaConvert(L, -1); 151 | if (!arg) { 152 | Py_DECREF(args); 153 | Py_DECREF(pKywdArgs); 154 | return luaL_error(L, "failed to convert argument '%s'", lua_tostring(L, -2)); 155 | } 156 | PyDict_SetItemString(pKywdArgs, lua_tostring(L, -2), arg); 157 | Py_DECREF(arg); 158 | } 159 | lua_pop(L, 1); 160 | } 161 | } 162 | // regular call style e.g. plt.plot(x, y) 163 | else { 164 | args = PyTuple_New(nargs); 165 | if (!args) { 166 | PyErr_Print(); 167 | return luaL_error(L, "failed to create arguments tuple"); 168 | } 169 | for (i = 0; i != nargs; i++) { 170 | PyObject *arg = LuaConvert(L, i+2); 171 | if (!arg) { 172 | Py_DECREF(args); 173 | return luaL_error(L, "failed to convert argument #%d", i+1); 174 | } 175 | PyTuple_SetItem(args, i, arg); 176 | } 177 | } 178 | 179 | value = PyObject_Call(obj->o, args, pKywdArgs); 180 | Py_DECREF(args); 181 | if (pKywdArgs) Py_DECREF(pKywdArgs); 182 | 183 | if (value) { 184 | ret = py_convert(L, value); 185 | Py_DECREF(value); 186 | } else { 187 | char s_exc[1024] = {0}; 188 | char s_traceback[1024] = {0}; 189 | 190 | PyObject *exc_type, *exc_value, *exc_traceback; 191 | PyErr_Fetch(&exc_type, &exc_value, &exc_traceback); 192 | PyErr_NormalizeException(&exc_type, &exc_value, &exc_traceback); 193 | 194 | PyObject *exc_str = PyObject_Str(exc_value); 195 | 196 | // Need not be garbage collected as per documentation of PyUnicode_AsUTF8 197 | const char *exc_cstr = (exc_str)?PyUnicode_AsUTF8(exc_str):""; 198 | strncpy(s_exc, (!(exc_cstr)?"UNKNOWN ERROR\n":exc_cstr), 1023); 199 | 200 | if (exc_value != NULL && exc_traceback != NULL) { 201 | PyObject *traceback_module = PyImport_ImportModule("traceback"); 202 | if (traceback_module != NULL) { 203 | PyObject *traceback_list = PyObject_CallMethod(traceback_module, 204 | "format_exception", "OOO", exc_type, exc_value, exc_traceback); 205 | if (traceback_list != NULL) { 206 | PyObject *traceback_str = PyUnicode_Join(PyUnicode_FromString(""), traceback_list); 207 | if (traceback_str != NULL) { 208 | // Need not be garbage collected as per documentation of PyUnicode_AsUTF8 209 | const char *traceback_cstr = PyUnicode_AsUTF8(traceback_str); 210 | if (traceback_cstr != NULL) { 211 | strncpy(s_traceback, traceback_cstr, 1023); 212 | } 213 | Py_XDECREF(traceback_str); 214 | } 215 | Py_XDECREF(traceback_list); 216 | } 217 | Py_XDECREF(traceback_module); 218 | } 219 | } 220 | Py_XDECREF(exc_type); 221 | Py_XDECREF(exc_value); 222 | Py_XDECREF(exc_traceback); 223 | Py_XDECREF(exc_str); 224 | 225 | if (*s_traceback == '\0') { 226 | luaL_error(L, "error calling python function:\nException: %s", s_exc); 227 | } 228 | else { 229 | luaL_error(L, "error calling python function:\nException: %s", s_traceback); 230 | } 231 | 232 | } 233 | 234 | return ret; 235 | } 236 | 237 | static int _p_object_newindex_set(lua_State *L, py_object *obj, 238 | int keyn, int valuen) 239 | { 240 | PyObject *value; 241 | PyObject *key = LuaConvert(L, keyn); 242 | 243 | if (!key) { 244 | return luaL_argerror(L, 1, "failed to convert key"); 245 | } 246 | 247 | if (!lua_isnil(L, valuen)) { 248 | value = LuaConvert(L, valuen); 249 | if (!value) { 250 | Py_DECREF(key); 251 | return luaL_argerror(L, 1, "failed to convert value"); 252 | } 253 | 254 | if (PyObject_SetItem(obj->o, key, value) == -1) { 255 | PyErr_Print(); 256 | luaL_error(L, "failed to set item"); 257 | } 258 | 259 | Py_DECREF(value); 260 | } else { 261 | if (PyObject_DelItem(obj->o, key) == -1) { 262 | PyErr_Print(); 263 | luaL_error(L, "failed to delete item"); 264 | } 265 | } 266 | 267 | Py_DECREF(key); 268 | return 0; 269 | } 270 | 271 | static int py_object_newindex_set(lua_State *L) 272 | { 273 | py_object *obj = (py_object*) luaL_checkudata(L, lua_upvalueindex(1), POBJECT); 274 | if (lua_gettop(L) != 2) 275 | return luaL_error(L, "invalid arguments"); 276 | 277 | return _p_object_newindex_set(L, obj, 1, 2); 278 | } 279 | 280 | static int py_object_newindex(lua_State *L) 281 | { 282 | PyObject *value; 283 | const char *attr; 284 | py_object *obj = (py_object*) luaL_checkudata(L, 1, POBJECT); 285 | assert(obj); 286 | 287 | if (obj->asindx || lua_type(L, 2) != LUA_TSTRING) 288 | return _p_object_newindex_set(L, obj, 2, 3); 289 | 290 | attr = luaL_checkstring(L, 2); 291 | assert(attr); 292 | 293 | value = LuaConvert(L, 3); 294 | if (!value) { 295 | return luaL_argerror(L, 1, "failed to convert value"); 296 | } 297 | 298 | if (PyObject_SetAttrString(obj->o, attr, value) == -1) { 299 | Py_DECREF(value); 300 | PyErr_Print(); 301 | return luaL_error(L, "failed to set value"); 302 | } 303 | 304 | Py_DECREF(value); 305 | return 0; 306 | } 307 | 308 | static int _p_object_index_get(lua_State *L, py_object *obj, int keyn) 309 | { 310 | PyObject *key = LuaConvert(L, keyn); 311 | PyObject *item; 312 | int ret = 0; 313 | 314 | if (!key) { 315 | return luaL_argerror(L, 1, "failed to convert key"); 316 | } 317 | 318 | item = PyObject_GetItem(obj->o, key); 319 | if (!item) { 320 | item = PyObject_GetAttr(obj->o, key); 321 | } 322 | 323 | Py_DECREF(key); 324 | 325 | if (item) { 326 | ret = py_convert(L, item); 327 | Py_DECREF(item); 328 | } else { 329 | PyErr_Clear(); 330 | if (lua_gettop(L) > keyn) { 331 | lua_pushvalue(L, keyn+1); 332 | ret = 1; 333 | } 334 | } 335 | 336 | return ret; 337 | } 338 | 339 | static int py_object_index_get(lua_State *L) 340 | { 341 | py_object *obj = (py_object*) luaL_checkudata(L, lua_upvalueindex(1), POBJECT); 342 | int top = lua_gettop(L); 343 | if (top < 1 || top > 2) 344 | return luaL_error(L, "invalid arguments"); 345 | 346 | return _p_object_index_get(L, obj, 1); 347 | } 348 | 349 | static int py_object_index(lua_State *L) 350 | { 351 | int ret = 0; 352 | PyObject *value; 353 | const char *attr; 354 | py_object *obj = (py_object*) luaL_checkudata(L, 1, POBJECT); 355 | assert(obj); 356 | 357 | if (obj->asindx || lua_type(L, 2) != LUA_TSTRING) 358 | return _p_object_index_get(L, obj, 2); 359 | 360 | attr = luaL_checkstring(L, 2); 361 | assert(attr); 362 | 363 | if (strcmp(attr, "__get") == 0) { 364 | lua_pushvalue(L, 1); 365 | lua_pushcclosure(L, py_object_index_get, 1); 366 | return 1; 367 | } else if (strcmp(attr, "__set") == 0) { 368 | lua_pushvalue(L, 1); 369 | lua_pushcclosure(L, py_object_newindex_set, 1); 370 | return 1; 371 | } 372 | 373 | 374 | value = PyObject_GetAttrString(obj->o, attr); 375 | if (value) { 376 | ret = py_convert(L, value); 377 | Py_DECREF(value); 378 | } else { 379 | PyErr_Clear(); 380 | lua_pushnil(L); 381 | ret = 1; 382 | } 383 | 384 | return ret; 385 | } 386 | 387 | static int py_object_gc(lua_State *L) 388 | { 389 | py_object *obj = (py_object*) luaL_checkudata(L, 1, POBJECT); 390 | assert(obj); 391 | 392 | Py_DECREF(obj->o); 393 | return 0; 394 | } 395 | 396 | static int py_object_tostring(lua_State *L) 397 | { 398 | py_object *obj = (py_object*) luaL_checkudata(L, 1, POBJECT); 399 | assert(obj); 400 | 401 | PyObject *repr = PyObject_Str(obj->o); 402 | if (!repr) 403 | { 404 | char buf[256]; 405 | snprintf(buf, 256, "python object: %p", (void *)obj->o); 406 | lua_pushstring(L, buf); 407 | PyErr_Clear(); 408 | } 409 | else 410 | { 411 | py_convert(L, repr); 412 | assert(lua_type(L, -1) == LUA_TSTRING); 413 | Py_DECREF(repr); 414 | } 415 | return 1; 416 | } 417 | 418 | static int py_operator_lambda(lua_State *L, const char *op) 419 | { 420 | static char script_buff[] = "lambda a, b: a b"; 421 | static size_t len = sizeof(script_buff) / sizeof(script_buff[0]); 422 | snprintf(script_buff, len, "lambda a, b: a %s b", op); 423 | 424 | lua_pushcfunction(L, py_eval); 425 | lua_pushlstring(L, script_buff, len); 426 | lua_call(L, 1, 1); 427 | return luaL_ref(L, LUA_REGISTRYINDEX); 428 | } 429 | 430 | #define make_pyoperator(opname, opliteral) \ 431 | static int py_object_ ## opname(lua_State *L) \ 432 | { \ 433 | static int op_ref = LUA_REFNIL; \ 434 | if (op_ref == LUA_REFNIL) op_ref = py_operator_lambda(L, opliteral); \ 435 | \ 436 | lua_rawgeti(L, LUA_REGISTRYINDEX, op_ref); \ 437 | lua_insert(L, 1); \ 438 | return py_object_call(L); \ 439 | } \ 440 | struct opname ## __LINE__ // force semi 441 | 442 | make_pyoperator(_pow, "**"); 443 | make_pyoperator(_mul, "*"); 444 | make_pyoperator(_div, "/"); 445 | make_pyoperator(_add, "+"); 446 | make_pyoperator(_sub, "-"); 447 | 448 | static const luaL_Reg py_object_mt[] = 449 | { 450 | {"__call", py_object_call}, 451 | {"__index", py_object_index}, 452 | {"__newindex", py_object_newindex}, 453 | {"__gc", py_object_gc}, 454 | {"__tostring", py_object_tostring}, 455 | {"__pow", py_object__pow}, 456 | {"__mul", py_object__mul}, 457 | {"__div", py_object__div}, 458 | {"__add", py_object__add}, 459 | {"__sub", py_object__sub}, 460 | {NULL, NULL} 461 | }; 462 | 463 | static int py_run(lua_State *L, int eval) 464 | { 465 | const char *s = luaL_checkstring(L, 1); 466 | PyObject *m, *d, *o; 467 | int ret = 0; 468 | 469 | lua_settop(L, 1); 470 | 471 | if (!eval) 472 | { 473 | lua_pushliteral(L, "\n"); 474 | lua_concat(L, 2); 475 | 476 | s = luaL_checkstring(L, 1); 477 | } 478 | 479 | m = PyImport_AddModule("__main__"); 480 | if (!m) 481 | return luaL_error(L, "Can't get __main__ module"); 482 | 483 | d = PyModule_GetDict(m); 484 | 485 | o = PyRun_String(s, eval ? Py_eval_input : Py_file_input, 486 | d, d); 487 | if (!o) 488 | { 489 | PyErr_Print(); 490 | return 0; 491 | } 492 | 493 | if (py_convert(L, o)) 494 | ret = 1; 495 | 496 | Py_DECREF(o); 497 | 498 | #if PY_MAJOR_VERSION < 3 499 | if (Py_FlushLine()) 500 | #endif 501 | PyErr_Clear(); 502 | 503 | return ret; 504 | } 505 | 506 | static int py_execute(lua_State *L) 507 | { 508 | return py_run(L, 0); 509 | } 510 | 511 | static int py_eval(lua_State *L) 512 | { 513 | return py_run(L, 1); 514 | } 515 | 516 | static int py_asindx(lua_State *L) 517 | { 518 | py_object *obj = (py_object*) luaL_checkudata(L, 1, POBJECT); 519 | assert(obj); 520 | 521 | return py_convert_custom(L, obj->o, 1); 522 | } 523 | 524 | static int py_asattr(lua_State *L) 525 | { 526 | py_object *obj = (py_object*) luaL_checkudata(L, 1, POBJECT); 527 | assert(obj); 528 | 529 | return py_convert_custom(L, obj->o, 0); 530 | } 531 | 532 | static int py_asfunc_call(lua_State *L) 533 | { 534 | lua_pushvalue(L, lua_upvalueindex(1)); 535 | lua_insert(L, 1); 536 | return py_object_call(L); 537 | } 538 | 539 | static int py_asfunc(lua_State *L) 540 | { 541 | py_object *obj = luaL_checkudata(L, 1, POBJECT); 542 | if (!PyCallable_Check(obj->o)) 543 | return luaL_error(L, "object is not callable"); 544 | 545 | lua_settop(L, 1); 546 | lua_pushcclosure(L, py_asfunc_call, 1); 547 | 548 | return 1; 549 | } 550 | 551 | static int py_globals(lua_State *L) 552 | { 553 | PyObject *globals; 554 | 555 | if (lua_gettop(L) != 0) { 556 | return luaL_error(L, "invalid arguments"); 557 | } 558 | 559 | globals = PyEval_GetGlobals(); 560 | if (!globals) { 561 | PyObject *module = PyImport_AddModule("__main__"); 562 | if (!module) { 563 | return luaL_error(L, "Can't get __main__ module"); 564 | } 565 | globals = PyModule_GetDict(module); 566 | } 567 | 568 | if (!globals) { 569 | PyErr_Print(); 570 | return luaL_error(L, "can't get globals"); 571 | } 572 | 573 | return py_convert_custom(L, globals, 1); 574 | } 575 | 576 | static int py_locals(lua_State *L) 577 | { 578 | PyObject *locals; 579 | 580 | if (lua_gettop(L) != 0) { 581 | return luaL_error(L, "invalid arguments"); 582 | } 583 | 584 | locals = PyEval_GetLocals(); 585 | if (!locals) 586 | return py_globals(L); 587 | 588 | return py_convert_custom(L, locals, 1); 589 | } 590 | 591 | static int py_builtins(lua_State *L) 592 | { 593 | PyObject *builtins; 594 | 595 | if (lua_gettop(L) != 0) { 596 | return luaL_error(L, "invalid arguments"); 597 | } 598 | 599 | builtins = PyEval_GetBuiltins(); 600 | if (!builtins) { 601 | PyErr_Print(); 602 | return luaL_error(L, "failed to get builtins"); 603 | } 604 | 605 | return py_convert_custom(L, builtins, 1); 606 | } 607 | 608 | static int py_import(lua_State *L) 609 | { 610 | const char *name = luaL_checkstring(L, 1); 611 | PyObject *module = PyImport_ImportModule((char*)name); 612 | int ret; 613 | 614 | if (!module) 615 | { 616 | PyErr_Print(); 617 | return luaL_error(L, "failed importing '%s'", name); 618 | } 619 | 620 | ret = py_convert_custom(L, module, 0); 621 | Py_DECREF(module); 622 | return ret; 623 | } 624 | 625 | py_object* luaPy_to_pobject(lua_State *L, int n) 626 | { 627 | if(!lua_getmetatable(L, n)) return NULL; 628 | luaL_getmetatable(L, POBJECT); 629 | int is_pobject = lua_rawequal(L, -1, -2); 630 | lua_pop(L, 2); 631 | 632 | return is_pobject ? (py_object *) lua_touserdata(L, n) : NULL; 633 | } 634 | 635 | static const luaL_Reg py_lib[] = 636 | { 637 | {"execute", py_execute}, 638 | {"eval", py_eval}, 639 | {"asindx", py_asindx}, 640 | {"asattr", py_asattr}, 641 | {"asfunc", py_asfunc}, 642 | {"locals", py_locals}, 643 | {"globals", py_globals}, 644 | {"builtins", py_builtins}, 645 | {"import", py_import}, 646 | {NULL, NULL} 647 | }; 648 | 649 | LUA_API int luaopen_python(lua_State *L) 650 | { 651 | int rc; 652 | 653 | /* Register module */ 654 | luaL_newlib(L, py_lib); 655 | 656 | /* Register python object metatable */ 657 | luaL_newmetatable(L, POBJECT); 658 | luaL_setfuncs(L, py_object_mt, 0); 659 | lua_pop(L, 1); 660 | 661 | /* Initialize Lua state in Python territory */ 662 | if (!LuaState) LuaState = L; 663 | 664 | /* Initialize Python interpreter */ 665 | if (!Py_IsInitialized()) 666 | { 667 | PyObject *luam, *mainm, *maind; 668 | #if PY_MAJOR_VERSION >= 3 669 | wchar_t *argv[] = {L"", 0}; 670 | #else 671 | char *argv[] = {"", 0}; 672 | #endif 673 | Py_SetProgramName(argv[0]); 674 | PyImport_AppendInittab("lua", PyInit_lua); 675 | 676 | /* Loading python library symbols so that dynamic extensions don't throw symbol not found error. 677 | Ref Link: http://stackoverflow.com/questions/29880931/importerror-and-pyexc-systemerror-while-embedding-python-script-within-c-for-pam 678 | */ 679 | #if defined(__linux__) 680 | # define STR(s) #s 681 | # define PYLIB_STR(s) STR(s) 682 | #if !defined(PYTHON_LIBRT) 683 | # error PYTHON_LIBRT must be defined when building under Linux! 684 | #endif 685 | void *ok = dlopen(PYLIB_STR(PYTHON_LIBRT), RTLD_NOW | RTLD_GLOBAL); 686 | assert(ok); (void) ok; 687 | #endif 688 | 689 | Py_Initialize(); 690 | PySys_SetArgv(1, argv); 691 | /* Import 'lua' automatically. */ 692 | luam = PyImport_ImportModule("lua"); 693 | if (!luam) 694 | return luaL_error(L, "Can't import lua module"); 695 | 696 | mainm = PyImport_AddModule("__main__"); 697 | if (!mainm) 698 | { 699 | Py_DECREF(luam); 700 | return luaL_error(L, "Can't get __main__ module"); 701 | } 702 | 703 | maind = PyModule_GetDict(mainm); 704 | PyDict_SetItemString(maind, "lua", luam); 705 | Py_DECREF(luam); 706 | } 707 | 708 | /* Register 'none' */ 709 | rc = py_convert_custom(L, Py_None, 0); 710 | if (!rc) 711 | return luaL_error(L, "failed to convert none object"); 712 | 713 | lua_pushvalue(L, -1); 714 | lua_setfield(L, LUA_REGISTRYINDEX, "Py_None"); /* registry.Py_None */ 715 | 716 | lua_setfield(L, -2, "none"); /* python.none */ 717 | 718 | return 1; 719 | } 720 | -------------------------------------------------------------------------------- /src/pythoninlua.h: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Lunatic Python 4 | -------------- 5 | 6 | Copyright (c) 2002-2005 Gustavo Niemeyer 7 | 8 | This library is free software; you can redistribute it and/or 9 | modify it under the terms of the GNU Lesser General Public 10 | License as published by the Free Software Foundation; either 11 | version 2.1 of the License, or (at your option) any later version. 12 | 13 | This library is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 16 | Lesser General Public License for more details. 17 | 18 | You should have received a copy of the GNU Lesser General Public 19 | License along with this library; if not, write to the Free Software 20 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 21 | 22 | */ 23 | #ifndef PYTHONINLUA_H 24 | #define PYTHONINLUA_H 25 | 26 | #define POBJECT "POBJECT" 27 | 28 | #if PY_MAJOR_VERSION < 3 29 | #define PyBytes_Check PyString_Check 30 | #define PyBytes_AsStringAndSize PyString_AsStringAndSize 31 | #endif 32 | 33 | int py_convert(lua_State *L, PyObject *o); 34 | 35 | typedef struct 36 | { 37 | PyObject *o; 38 | int asindx; 39 | } py_object; 40 | 41 | py_object* luaPy_to_pobject(lua_State *L, int n); 42 | LUA_API int luaopen_python(lua_State *L); 43 | 44 | #endif 45 | -------------------------------------------------------------------------------- /tests/test_lua.py: -------------------------------------------------------------------------------- 1 | """ 2 | >>> lg = lua.globals() 3 | >>> lg == lg._G 4 | True 5 | >>> lg._G == lg._G 6 | True 7 | >>> lg._G == lg['_G'] 8 | True 9 | 10 | >>> lg.foo = 'bar' 11 | >>> lg.foo == u'bar' 12 | True 13 | 14 | >>> lg.tmp = [] 15 | >>> lg.tmp 16 | [] 17 | 18 | >>> lua.execute("x = {1, 2, 3, foo = {4, 5}}") 19 | >>> lg.x[1], lg.x[2], lg.x[3] 20 | (1..., 2..., 3...) 21 | >>> lg.x['foo'][1], lg.x['foo'][2] 22 | (4..., 5...) 23 | 24 | >>> lua.require 25 | 26 | 27 | >>> lg.string 28 | 29 | >>> lg.string.lower 30 | 31 | >>> lg.string.lower("Hello world!") == u'hello world!' 32 | True 33 | 34 | >>> d = {} 35 | >>> lg.d = d 36 | >>> lua.execute("d['key'] = 'value'") 37 | >>> d 38 | {...'key': ...'value'} 39 | 40 | >>> d2 = lua.eval("d") 41 | >>> d is d2 42 | True 43 | 44 | >>> lua.execute("python = require 'python'") 45 | >>> lua.eval("python") 46 | 47 | 48 | >>> obj 49 | 50 | 51 | >>> lua.eval("python.eval 'obj'") 52 | 53 | 54 | >>> lua.eval(\"\"\"python.eval([[lua.eval('python.eval("obj")')]])\"\"\") 55 | 56 | 57 | >>> lua.execute("pg = python.globals()") 58 | >>> lua.eval("pg.obj") 59 | 60 | 61 | >>> def show(key, value): 62 | ... print("key is %s and value is %s" % (repr(key), repr(value))) 63 | ... 64 | >>> asfunc = lua.eval("python.asfunc") 65 | >>> asfunc 66 | 67 | 68 | >>> l = ['a', 'b', 'c'] 69 | >>> t = lua.eval("{a=1, b=2, c=3}") 70 | >>> for k in l: 71 | ... show(k, t[k]) 72 | key is 'a' and value is 1... 73 | key is 'b' and value is 2... 74 | key is 'c' and value is 3... 75 | 76 | """ 77 | 78 | import sys, os 79 | sys.path.append(os.getcwd()) 80 | 81 | 82 | class MyClass: 83 | def __repr__(self): return '' 84 | 85 | obj = MyClass() 86 | 87 | 88 | if __name__ == '__main__': 89 | import lua 90 | import doctest 91 | doctest.testmod(optionflags=doctest.ELLIPSIS) 92 | -------------------------------------------------------------------------------- /tests/test_py.lua: -------------------------------------------------------------------------------- 1 | python = require 'python' 2 | 3 | assert(nil == python.eval "None") 4 | assert(true == python.eval "True") 5 | assert(false == python.eval "False") 6 | 7 | assert(1 == python.eval "1") 8 | assert(1.5 == python.eval "1.5") 9 | 10 | assert("foo" == python.eval "b'foo'") 11 | assert("bar" == python.eval "u'bar'") 12 | 13 | pyglob = python.globals() 14 | d = {} 15 | pyglob.d = d 16 | -- This crashes if you've compiled the python.so to include another 17 | -- Lua interpreter, i.e., with -llua. 18 | python.execute "d['key'] = 'value'" 19 | assert(d.key == 'value', d.key) 20 | 21 | python.execute "d.key = 'newvalue'" 22 | assert(d.key == 'newvalue', d.key) 23 | 24 | -- Test operators on py containers 25 | l = python.eval "['hello']" 26 | assert(tostring(l * 3) == "['hello', 'hello', 'hello']") 27 | assert(tostring(l + python.eval "['bye']") == "['hello', 'bye']") 28 | 29 | -- Test that Python C module can access Py Runtime symbols 30 | ctypes = python.import 'ctypes' 31 | assert(tostring(ctypes):match "module 'ctypes'") 32 | 33 | -- Test multiple Python statement execution 34 | pytype = python.eval "type" 35 | python.execute 36 | [[ 37 | foo = 1 38 | bar = 2 39 | ]] 40 | 41 | assert(python.globals().foo == 1) 42 | assert(python.globals().bar == 2) 43 | 44 | python.execute 45 | [[ 46 | def throw_exc(): 47 | raise Exception("THIS EXCEPTION") 48 | ]] 49 | 50 | local status, exc = pcall(python.globals().throw_exc) 51 | assert(status == false) 52 | assert(exc == 53 | [[error calling python function: 54 | Exception: Traceback (most recent call last): 55 | File "", line 2, in throw_exc 56 | Exception: THIS EXCEPTION 57 | ]], exc) 58 | 59 | local b, e = string.find(exc, "Exception: ", 1); 60 | local ob, oe = b, e; 61 | while (b ~= nil) do 62 | ob, oe = b, e 63 | b, e = string.find(exc, "Exception: ", e+1) 64 | end 65 | local exc_s = (string.sub(exc, oe+1)) 66 | --assert((require "pl.stringx").strip(exc_s) == "THIS EXCEPTION"); 67 | 68 | --------------------------------------------------------------------------------